[Python-ideas] Add peekline(), peeklines(n) and optional maxlines argument to readlines()

John O'Connor jxo6948 at rit.edu
Fri Sep 30 03:23:26 CEST 2011


It seems there could be a cleaner way of reading the first n lines of
a file and additionally not seeking past those lines (ie peek). This
is obviously a trivial task for 1 line ie...
f.readline()
f.seek(0)
but one that I think would make sense to add to the IO implementation,
given that we already have readline, readlines, and peek I think
peekline() or peeklines(n) is only a natural addition. The argument
for doing so (in 3.3 of course), is primarily readability but also
that the maintenance burden *seems* like it would be low. This
addition would also be helpful and more concise where n > 1.

I think readlines() should also take an optional argument for a max
number of lines to read. It seems more common/helpful to me than
'hint' for max bytes. In n>1 case one could do...

f.readlines(maxlines=10)

or for the 'peek' case

f.peeklines(10)


I also didn't find any of the answers from
http://stackoverflow.com/questions/1767513/read-first-n-lines-of-a-file-in-python
to be very compelling.

I am more than willing to propose a patch if the idea(s) are supported.

- John



More information about the Python-ideas mailing list