Home ยป How to Get the Line Count of a File using python

How to Get the Line Count of a File using python

In this example we will show how to get the line count of a file

Example

The test file contains the following, notice the blank lines

this is line 1
this is line 2

this is another line
line to count

and another line

Open the file in read-only mode.

We then use a for loop, iterate through the object named f.

In each iteration, a line is read an we increase the value of variable after each iteration.

def linecount(filename):
    with open(filename) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print(linecount("linecount.txt"))

When you run this you will see something like this

>>> %Run linecount.py
7

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More