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

Nick Coghlan ncoghlan at gmail.com
Fri Sep 30 13:28:19 CEST 2011

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):

    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:
            # Oops, didn't get as many lines as we wanted


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list