[Python-ideas] Add peekline(), peeklines(n) and optional maxlines argument to readlines()
Eli Bendersky
eliben at gmail.com
Tue Oct 4 19:59:18 CEST 2011
On Fri, Sep 30, 2011 at 13:28, Nick Coghlan <ncoghlan at gmail.com> wrote:
>
> On Fri, Sep 30, 2011 at 5:42 AM, Giampaolo Rodolà <g.rodola at gmail.com> wrote:
> > ...or 2 in case you're not at the beginning of the file.
> > before = f.tell()
> > f.peeklines(10)
> > f.seek(before)
>
> A context manager to handle the tell()/seek() may be an interesting
> and more general purpose idea:
>
> # In the io module
> class _TellSeek:
> def __init__(self, f):
> self._f = f
> def __enter__(self):
> self._position = self._f.tell()
> def __exit__(self, *args):
> self._f.seek(self._position)
>
> def restore_position(f):
> return _TellSeek(f)
>
> # Usage
> with io.restore_position(f):
> for i, line in enumerate(f, 1):
> # Do stuff
> if i == 10:
> break
> else:
> # Oops, didn't get as many lines as we wanted
This is useful, and made simpler by contextlib.contextmanager.
Actually I just posted this snipped on G+ a couple of weeks ago, since
I found it very useful for some stream-massaging code I was writing.
And yes, it only makes sense for seekable streams, of course.
So I'm -1 on the peeklines request, since it's easily implemented by
other means.
Eli
More information about the Python-ideas
mailing list