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:-

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

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

You may also like...


Warning: Undefined variable $category in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/sidebar_tutorial.php on line 10

Warning: Trying to access array offset on null in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/sidebar_tutorial.php on line 10

Warning: Attempt to read property "category_parent" on null in /www/wwwroot/followtutorials.com/wp-content/themes/hueman/sidebar_tutorial.php on line 10
Share