python-tutorialsmade

Read a file in Python and find number of Lines

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:

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:

 

I hope this helped someone, Good Luck!

Related Posts

Leave a Reply