How to count lines in a text file ?

Alex Martelli aleaxit at yahoo.com
Thu Sep 23 02:59:09 EDT 2004


Andrew Dalke <adalke at mindspring.com> wrote:

> Alex Martelli wrote:
> > ....and wc would then not count that non-line as a line, so why should
> > we...?  Witness...:
> 
>    'Cause that's what Python does.  Witness:

If you tell it to count non-lines too (pieces that don't end with an
endline marker), it does, of course:

> % echo -n 'bu' | python -c \
> ?       'import sys; print len(sys.stdin.readlines())'
> 1

But that's just because you told it to.

To reproduce wc's behavior, you have to exclude non-lines -- use
len([ l for l in sys.stdin if l.endswith('\n') ]) for example.  Or, the
simpler .count('\n') approach.

I suspect somebody who asks the subject question wants to reproduce wc's
counting behavior.  Of course, it _is_ an imprecise spec they're giving.


Alex



More information about the Python-list mailing list