/  Technology   /  How to get line count of a large file in Python?

How to get line count of a large file in Python?

 

In this article, we’ll discuss two efficient ways to find the count of the number of lines, as low as one or as high as a hundred thousand, present in any text file.

line count

 

Method 1:

Let’s consider this text file named “mytextfile.txt” for our example. It is a 14 line long text file.

 

Example:

Hello
I
am
a
Computer
Science
Student
I
learn
from

\\\
i2 tutorials
\\\

Output:

 

Example:

filename="mytextfile.txt"
count_lines=0
with open(filename, 'r') as files:
   for i in files:
      count_lines=count_lines+1

print()
print(count_lines)

Output:

 

Here we have opened our file “mytextfile.txt” in read mode. And using the count_lines we are able to print the number of lines present in the text file.

 

Method 2:

This is the fastest and also the most efficient one-liner code to count the number lines present in a text file. It comparatively takes less memory and time.

 

Example:

count_lines = sum(1 for line in open('mytextfile.txt'))
print(count_lines)

Output:

 

Note: Make sure that the text file and the python program file are present in the same directory, else we need to specify the entire path to the text file in the place of the filename.

 

Leave a comment