How to count lines in a text file ?

Alex Martelli aleaxit at yahoo.com
Wed Sep 22 17:17:12 EDT 2004


Andrew Dalke <adalke at mindspring.com> wrote:

> Bengt Richter wrote:
> > or, if you _are_ willing to read in the whole file,
> > 
> >     open('text.txt').read().count('\n')
> 
> Except the last line might not have a terminal newline.

...and wc would then not count that non-line as a line, so why should
we...?  Witness...:

$ echo -n 'bu'>em 
$ wc em
       0       1       2 em

zero lines, one word, two characters: seems right to me.


Alex



More information about the Python-list mailing list