Does Python support a peek like method for its file objects?

Blair P. Houghton blair.houghton at gmail.com
Sun Feb 5 03:30:55 EST 2006


Avi Kak wrote:
> Hello:
>
>   Does Python support a peek like method for its file objects?
>
>   I'd like to be able to look at the next byte in a disk file before
>   deciding whether I should read it with, say, the read() method.
>   Is it possible to do so in Python?
>
>   Your answer would be much appreciated.

If it's a seekable file (not a stream input) then you can use
file.tell() to get the current position, then file.read() to read
some data, then file.seek(), giving it the position you got from
file.tell(), to rewind to the same position.  This is the safe version;
in the unsafe version you can skip the file.tell() stuff and just use
relative positioning in the file.seek() operation.

If it's a socket, you can use recv() or recvfrom() if you
set the flags argument to MSG_PEEK.

If it's a stream, you're out of luck, and you'll have to buffer the
data
yourself, although you can use select() or poll() to check on
availability of data if that's what you really want.

At least, in theory.  I haven't tried any of this in Python yet.

--Blair




More information about the Python-list mailing list