On Fri, Sep 30, 2011 at 5:42 AM, Giampaolo Rodolà <g.rodola@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 Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia