how do I "peek" into the next line?

Peter Otten __peter__ at web.de
Mon Dec 13 15:40:40 EST 2004


les_ander at yahoo.com wrote:

> Hi,
> suppose I am reading lines from a file or stdin.
> I want to just "peek" in to the next line, and if it starts
> with a special character I want to break out of a for loop,
> other wise I want to do readline().
> 
> Is there a way to do this?
> for example:
> while 1:
> line=stdin.peek_nextline()
> if not line: break
> if line[0]=="|":
> break:
> else:
>     x=stdin.nextline()
>     # do something with x
> 
> thanks

The itertools approach:

(some preparations)

>>> import itertools
>>> file("tmp.txt", "w").write("""\
... a
... b
... c
... |
... d
... e
... f
... """)

(1) You are only interested in lines after and including the "special" line:

>>> def predicate(line):
...     return not line.startswith("|")
...
>>> for line in itertools.dropwhile(predicate, file("tmp.txt")):
...     print line,
...
|
d
e
f

(2) You want both the "head" and the "tail", where the tail includes the
"special" line:

>>> lines = iter(file("tmp.txt"))
>>> for line in lines:
...     if line.startswith("|"):
...             lines = itertools.chain([line], lines)
...             break
...     print "head", line,
...
head a
head b
head c
>>> for line in lines:
...     print "tail", line,
...
tail |
tail d
tail e
tail f
>>>

Peter




More information about the Python-list mailing list