how do I "peek" into the next line?

Steven Bethard steven.bethard at gmail.com
Mon Dec 13 17:02:49 EST 2004


les_ander at yahoo.com wrote:
> now suppose I have read the first line already.
> then I read the second line and notice
> that there is a ">" in front (my special character)
> then I want the put back the second line into the
> file or the stdin.

Another possibility -- have each call to __iter__ produce the next 
"section" of your data:

 >>> class strangefileiter(object):
...     def __init__(self, file):
...         self.iter = peekable(file)
...         self.yield_last = False
...     def __iter__(self):
...         if self.yield_last:
...             yield self.iter.next()
...             self.yield_last = False
...         while True:
...             next = self.iter.peek()
...             if next.rstrip('\n') == "|":
...                 self.yield_last = True
...                 break
...             yield self.iter.next()
...
 >>> f = strangefileiter(file('temp.txt'))
 >>> file('temp.txt', 'w').write("""\
... text
... before first |
... |
... text after
... first |
... |
... final text""")
 >>> f = strangefileiter(file('temp.txt'))
 >>> for line in f:
...     print repr(line)
...
'text\n'
'before first |\n'
 >>> for line in f:
...     print repr(line)
...
'|\n'
'text after\n'
'first |\n'
 >>> for line in f:
...     print repr(line)
...
'|\n'
'final text'

I'm not sure I'd do it this way -- it makes me a little nervous that 
each call to __iter__ iterates over something different.  But it might 
be closer to what you were trying to do...

Steve



More information about the Python-list mailing list