Graceful detection of EOF

Jeff Epler jepler at
Thu Oct 7 21:37:59 CEST 2004

Write a file-like object that can "look ahead" and provide a flag to
check in your unpickling loop, and which implements enough of the file
protocol ("read" and "readline", apparently) to please pickle.  The
following worked for me.

class PeekyFile:
    def __init__(self, f):
        self.f = f
        self.peek = ""

    def eofnext(self):
        if self.peek: return False
            self.peek =
        except EOFError:
            return True
        return not self.peek

    def read(self, n=None):
        if n is not None:
            n = n - len(self.peek)
            result = self.peek +
            result = self.peek +
        self.peek = ""
        return result

    def readline(self):
        result = self.peek + self.f.readline()
        self.peek = ""
        return result

import StringIO, pickle
o = StringIO.StringIO()
for x in range(5):
    pickle.dump(x, o)
i = PeekyFile(StringIO.StringIO(o.getvalue()))
while 1:
    if i.eofnext():
    print pickle.load(i)
print "at the end"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list