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
  • 100,514
  • 17
  • 155
  • 179
user3601754
  • 3,552
  • 11
  • 40
  • 72

4 Answers4

28

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
  • 100,514
  • 17
  • 155
  • 179
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
  • 20,142
  • 17
  • 60
  • 81
The6thSense
  • 7,631
  • 6
  • 30
  • 63
5
with open('test.txt') as f:
    size=len([0 for _ in f])
saeedgnu
  • 3,823
  • 2
  • 29
  • 46
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
  • 303
  • 1
  • 11