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.
Amended iterator class example using my peekable recipe:
>>> class strangefileiter(object): ... def __init__(self, file): ... self.iter = peekable(file) ... def __iter__(self): ... while True: ... next = self.iter.peek() ... if not next or next.rstrip('\n') == "|": ... break ... yield self.iter.next() ... >>> file('temp.txt', 'w').write("""\ ... some text ... some more ... | ... not really text""") >>> f = strangefileiter(file('temp.txt')) >>> for line in f: ... print repr(line) ... 'some text\n' 'some more\n' >>> remainder = f.iter >>> for line in remainder: ... print repr(line) ... '|\n' 'not really text'
Note that because I wrap the file iterator with a peekable[1] object, the lines aren't consumed when I test them. So to access the remaining lines, I just use the iter field of the strangefileiter object.
Steve
[1] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 -- http://mail.python.org/mailman/listinfo/python-list