how to count lines in a file ?

Alex Martelli aleax at aleax.it
Thu Jul 25 04:52:53 EDT 2002


Fredrik Lundh wrote:

> Alex Martelli wrote:
> 
>> BTW, GvR claimed (less than a month ago on the python-dev list)
>> that having an integer argument to readlines was a design error.
> 
> except that he was talking about "readline", not "readlines".

Sorry, you're right.  The argumernt to readlines was not discussed.


> (does anyone here even know that readline takes an optional
> integer argument, and what it does? ;-)

I would hope so, given that
http://www.python.org/doc/current/lib/bltin-file-objects.html
documents it so clearly.

Basically: all of read, readline, readlines methods take an
optional integer argument "maximum number of bytes to read".

HOWEVER, according to the docs, read and readline HAVE to
respect that argument and are never allowed to return more
than N bytes when called with an argument of N.

readlines, OTOH, takes its argument as just a hint and is
explicitly documented as being perfectly well allowed to
ignore it completely if impossible or inefficient to
implement, round it up when convenient, whatever.

f.readline(N) may return a partial, incomplete line if
that's the best it can do without exceedinng N bytes.

Docs for f.readlines(N) are not quite as clear on this
point, but it seems that readlines is NOT allowed to
return incomplete lines -- rather it should return more
than N bytes (as it's explicitly allowed to) if needed.

That's definitely what the current implementation does.

Module xreadlines (and thus f.xreadlines, which is
explicitly documented as being equivalent to a call to
xreadlines.xreadlines(f)) uses f.readlines(N) (both by
the docs, and by the implementation).


Alex




More information about the Python-list mailing list