Showing posts with label display file with line number. Show all posts
Showing posts with label display file with line number. Show all posts

Java - File handling - display file with line number

// File handling

/*
Write a Java program that reads a file and displays the file on the screen, with a line number before each line.
*/

import java.io.*;

class FileLineDisplay
{
     public static void main(String as[]) throws IOException
     {
          FileReader fr = new FileReader("ipt.txt");
          BufferedReader br = new BufferedReader(fr);

          int linecount=1;

          while(true)
          {
              String str = br.readLine();
              if(str==null)
                   break;
              System.out.print(linecount+" "+str+"\n");
              linecount++;
          }
          fr.close();
     }
}

File Handling 3: Display file content with line number

# Display file content with line number
# Use command line arguments

import sys

fname = sys.argv[1]

fs = open(fname, "r")
Line_num = 1

print("File:", fs.name)

while(True):
Line = fs.readline()

if not Line:
break

print(Line_num, Line)
Line_num += 1

fs.close()


# Display file content with line number
# Use command line arguments

import sys

fname = sys.argv[1]
fs = open(fname, "r")

print("File:", fs.name)

L = fs.readlines()
for Line in L:
print(L.index(Line)+1, Line)

fs.close()