Python - How to get the number of lines in a text file

41,060

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
Share:
41,060
user3601754
Author by

user3601754

Updated on July 09, 2022

Comments

  • user3601754
    user3601754 almost 2 years

    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(text)
    

    My file is very huge so it s difficult to use this kind of approach...