Skip to content Skip to sidebar Skip to footer

Python - How To Get The Number Of Lines In A Text File

I would like to know if it s possible to know how many lines contains my file text without using a command as : with open('test.txt') as f: text = f.readlines() size = len(

Solution 1:

As a Pythonic approach you can count the number of lines using a generator expression within sum function as following:

with open('test.txt') as f:
   count = sum(1 for _ in f)

Note that here the fileobject f is an iterator object that represents an iterator of file's lines.


Solution 2:

Slight modification to your approach

with open('test.txt') as f:
    line_count = 0
    for line in f:
        line_count += 1

print line_count

Notes:

Here you would be going through line by line and will not load the complete file into the memory


Solution 3:

with open('test.txt') as f:
    size=len([0 for _ in f])

Solution 4:

The number of lines of a file is not stored in the metadata. So you actually have to run trough the whole file to figure it out. You can make it a bit more memory efficient though:

lines = 0
with open('test.txt') as f:
    for line in f:
        lines = lines + 1

Post a Comment for "Python - How To Get The Number Of Lines In A Text File"