John Doucette
John Doucette

Reputation: 4550

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.

Upvotes: 3

Views: 2773

Answers (3)

nadapez
nadapez

Reputation: 2727

file.read(1)
file.seek(file.tell()-1)

Upvotes: 1

winni2k
winni2k

Reputation: 1515

This does not work in text mode, but it does work in binary mode:

>>> open('test', 'rb').peek(1)
b'test\n'

Upvotes: 3

John Doucette
John Doucette

Reputation: 4550

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

Upvotes: 0

Related Questions