Reading a file in Python is very simple, In this tutorial you are going to see how to read a file as well as count the number of lines in a text file in Python.
See the code here:
1 2 3 4 5 6 7 8 |
f = open('myfile.txt') lines = f.readlines() total_lines = len(lines) print "No. of lines are " , total_lines , "\n" for line in lines: print line.rstrip() f.close() |
Looks simple isn’t it?.
NOTE: myfile.txt file should be there to run this program, otherwise program will throw an error saying file not found , it doesn’t mean you have to have the file name as ‘myfile.txt’ it can be any name.
What all functions used in this program?
open() – this is a built-in function in Python to open a file and it returns the object of the file type .
readlines() – this is again a built-in function in Python which helps to read a file line by line and it will automatically add a new line character at the end of the each line “\n”
len() – len is also a default Python function, this returns the number of items in an object.
rstrip() – this is also an built-in function which helps to remove the space or new line charter at the end of a string.
I have used rstrip() to remove the new line characters (\n) added by the readlines() function, if you don’t want to remove \n, just omit the rstrip() and put only print line in the above program (line no. 7)
Code with comments to understand:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#open myfile.txt, give exact path of the file here #for eg. if it is in C drive then 'c:/folder/myfile.txt' f = open('myfile.txt') #read line by line of the above opened file 'myfile.txt' lines = f.readlines() #count the no. of lines with the help of len() function total_lines = len(lines) print "No. of lines are " , total_lines , "\n" #use for loop to print each lines for line in lines: #strip the \n which is added by readlines() print line.rstrip() #finally close the file f.close() |
I hope this helped someone, Good Luck!