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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Feb 5 03:25:21 EST 2006


On Sun, 05 Feb 2006 05:45:24 +0000, 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?


# WARNING: untested

fp = file("some file on disk", "rb")
b = ""
while 1:
    # peek at the next byte
    c = fp.read(1)
    # decide whether to read it
    if c == "?":
        # pretend we never read the byte
        del c
        fp.seek(-1, 1)  # but be careful in text mode!
        break
    # now read the byte "for real"
    b = fp.read(1)
    if not b:
        # we've reached the end of the file
        break
fp.close()

I'm not sure exactly why you'd want to do this, but it should be doable,
at least for files that support seeking.



-- 
Steven.




More information about the Python-list mailing list