How to count the number of lines in a text file in Python
In order to learn how to count the number of lines in a text file in Python, you have to understand the
open()function in Python. In this tutorial, we will learn to count the number of lines in text files using Python.
If you already have a basic understanding of the Python
open() function, then let’s follow this tutorial…
Text files can be used in many situations. For example, you may save your in a text file or you may fetch the data of a text file in Python. In my previous tutorial, I have shown you how to create a text file in Python.
Now in this article, I will show you how to count the total number of lines in a text file.
In order to open a file, we need to use the
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 large files.
Here I am going to provide both of these techniques so that you can use the perfect one for you.
Assume that you have a text file in the same directory with the filename: this_is_file.txt . Suppose, this file contains the given text content that you can see below:
Hello I am first line I am the 2nd line I am oviously 3rd line
To get the number of lines in our text file below is the given Python program:
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 of large size
To handle large-size text file you can use the following Python program:
with open('this_is_file.txt') as my_file: print(sum(1 for _ in my_file))
If you have any doubts or suggestions you can simply write in the below comment section