How to count the number of lines in a text file in Python
In order to know how to count the number of lines in a text file in Python, you have to know open() function in Python. In this tutorial, we will learn to count the number of lines in text files using Python.
Text files can be used in many situations. For example, you may save your data with Python in a text file or you may fetch the data of a text file in Python. In my previous, I have shown you How to create a text file in Python
Now I will show you how to count the number of lines in a text file.
In order to open a file, we need to use the open() function.
Count the number of lines in a text file in Python
We can reach our aim with various techniques. Some of those can only deal with small to medium size text files and some techniques are able to handle the large files.
Here I am going to provide both the techniques so that you can use the perfect one for you.
Assume that you have a text file in the same directory with a filename: this_is_file.txt
Hello I am first line I am the 2nd line I am oviously 3rd line
The above is the content of the text file.
To get the number of lines in a text file you can use:
number_of_lines = len(open('this_is_file.txt').readlines( )) print(number_of_lines)
You may also learn,
Special Note: It can not deal with very large files. But it will work fine on small to medium size files
Count number of lines in a text file in Python for large size files
To handle large size text file you can use the following:
with open('this_is_file.txt') as my_file: print(sum(1 for _ in my_file))
If you have any doubts or suggestion you can simply write in the below comment section