Python txt – Count the number of lines in a text file

In this post we will be creating a Python script that will count the number of lines present within a text file, to do this we will be using a for loop that will iterate each line within the file.

See the snippet of code below where we count 1 for every line found within the specified text file.

num_lines = sum(1 for line in open('file.txt'))
print(num_lines)

Below is a snippet of our text file which we’ll be using for this example.

Example text file

With the above our script will output the following as the number of lines in the text file.

3
>>> 

Leave a Reply