Python Program to Count the Number of Lines in a Text File

In this example, we will write a python program to find the number of lines in a file. To better understand this example, make sure you have knowledge of the following tutorials:-

Loading...

Python Program to Count the Number of Lines in a Text File

Let us assume we have an about.txt file that contains the following paragraph.

A quick brown fox jumps over the lazy dog
A quick brown fox jumps over the lazy dog
A quick brown fox jumps over the lazy dog
A quick brown fox jumps over the lazy dog
The code for the program is:-
def count_lines(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1


print("Number of lines in the file: ", count_lines("about.txt"))

The output of the above program is:-

Number of lines in the file: 4

Loading...
SHARE Python Program to Count the Number of Lines in a Text File

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Share