how to count lines in a file ?
Chris Liechti
cliechti at gmx.net
Tue Jul 23 13:42:11 EDT 2002
"Shagshag13" <shagshag13 at yahoo.fr> wrote in news:ahk3la$tf3bh$1 at ID-
146704.news.dfncis.de:
> here is a test in counting [6871785] lines from a file of > 1Go
>
> ---
> lineCount = 0
> fhi = file(filename)
> for line in xreadlines.xreadlines(fhi):
note that a fileobject has an xreadlines method. no need to use the module
> lineCount += 1
>
> return lineCount
>
> [Eof processing] : 00:01:22
> ---
> lines = 0:
> for line in file(filename):
> lines += 1
>
> [Eof processing] : 00:01:22
it's not a coincidence that the times are equal as iterating through a file
with "for line in file()" is just a shortcut for "for line in
file().xreadlines()"
> ---
> lineCount = 0
> fp = open(filename)
> it = iter(fp)
> try:
> while it.next():
> lineCount += 1
> except StopIteration:
> pass
>
> return lineCount
>
> [Eof processing] : 00:01:42
as I just meantioned in an other message, that's just handcoding of "for
line in file()" and ignoring the "line" variable.
it is slower because the call to next is done in python, whereas the "for"
solution does this internally (in C).
all code you show is basicaly the same. the middle solution is the most
readble in my opinion.
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list