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

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


On Sun, 05 Feb 2006 19:25:21 +1100, Steven D'Aprano wrote:

> 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

Yes, and also completely broken. I don't know what I was thinking. Sigh.
Try this (also untested, but not so obviously broken):



fp = file("some file on disk", "r")  # should work in text mode
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
        fp.seek(-1, 1)  # but be careful in text mode! 
        break
    # now read the byte "for real"
    b = c
    if not b:
        # we've reached the end of the file
        break
fp.close()


-- 
Steven.




More information about the Python-list mailing list