How to count lines in a text file ?

Alex Martelli aleaxit at
Wed Sep 22 23:17:12 CEST 2004

Andrew Dalke <adalke at> 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.


More information about the Python-list mailing list