11

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

Mazdak
  • 105,000
  • 18
  • 159
  • 188
user3601754
  • 3,792
  • 11
  • 43
  • 77

4 Answers4

29

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.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
11

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

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
The6thSense
  • 8,103
  • 8
  • 31
  • 65
5
with open('test.txt') as f:
    size=len([0 for _ in f])
saeedgnu
  • 4,110
  • 2
  • 31
  • 48
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
Garogolun
  • 323
  • 2
  • 11