how to count lines in a file ?

Chris Liechti cliechti at gmx.net
Tue Jul 23 13:35:05 EDT 2002


"Denis S. Otkidach" <ods at fep.ru> wrote in 
news:mailman.1027443271.32201.python-list at python.org:

> fp = open(filename)
> it = iter(fp)
> try:
>     while it.next():
>         count += 1
> except StopIteration:
>     pass

just a little sidenote: what you have written here is correct but the same 
as:

for line in file(filename):
    	count += 1

the only little diffrence is that line is left bound to the last line. 
however I consider this as much more readable.
(the use "file" or "open" does not matter, i find "file" better readable in 
this context)

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list