how do I "peek" into the next line?

Skip Montanaro skip at pobox.com
Mon Dec 13 14:23:28 EST 2004


    les> suppose I am reading lines from a file or stdin.  I want to just
    les> "peek" in to the next line, and if it starts with a special
    les> character I want to break out of a for loop, other wise I want to
    les> do readline().

Create a wrapper around the file object:

    class PeekFile:
        def __init__(self, f):
            self.f = f
            self.last = None

        def push(self, line):
            self.last = line

        def readline(self):
            if self.last is not None:
                line = self.last
                self.last = None
                return line
            return self.f.readline()

        def __getattr__(self, attr):
            return getattr(self.f, attr)

Then use it like so:

    stdin = PeekFile(stdin)
    while 1:
        line = stdin.readline()
        if not line:
            break
        if line[0] == "|":
            stdin.push(line)
            break
        else:
            # do something with line

Of course, this could be tested (which my example hasn't been), PeekFile can
probably can be written as a subclass of the file class, and made more
generally robust (handle filenames as inputs instead of file objects,
support write modes, etc), but this should give you the general idea.

Skip




More information about the Python-list mailing list