Can you determine how many lines exist in a file without each iteration in a line?

Possible duplicate:
How to get the number of lines in Python cheaply?

Good afternoon. I have the code below that implements reading a line and a counter. 1/

def __set_quantity_filled_lines_in_file(self):
    count = 0
    with open(self.filename, 'r') as f:
        for line in f:
             count += 1
    return count

My question is: are there methods to determine the number of lines of text data in the current file without each iteration in a line?

Thank!

+3
source share
5 answers

In the general case, it is impossible to do better than reading each character in a file and counting newline characters.

, . , 1024 , 1 , , 1024 .

+4

, Python , , . \n ( ), , , .

+2

, ​​ ( ). , , ).

, . , len(f.readlines()) . , .

+1

readlines(), , , .

If you want to be different, you can use the read () member function to get the whole file and count CR, LF, CRLR LFCR character combinations using collections.Counter class.
However, you will have to deal with various ways of completing strings.
Sort of:

import collections
f=open("myfile","rb")
d=f.read()
f.close()
c=collections.Counter(d)
lines1=c['\r\n']
lines2=c['\n\r']
lines3=c['\r']-lines1-lines2
lines4=c['\n']-lines1-lines2
nlines=lines3+lines4
+1
source

This gives an answer, but reads the entire file and stores the lines in a list

    len(f.readlines())
0
source

All Articles