Search code examples
python-2.7python-3.xseekpeek

How can I peek at the next character in a file in Python 3?


Suppose I'm building a parser, and I want to lookahead in the stream.

In Python 2, I could write:

def peek():
    next = inputfile.read(1)
    inputfile.seek(-1,1)
    return next

however, in Python 3, relative seeks were disabled.


Solution

  • Instead, you can use inputfile.peek(1)[:1].