[Tutor] Detecting EOF

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 14 00:43:24 CEST 2004



On Thu, 7 Oct 2004, Robert Hines wrote:

> How do you detect the end of a file? Suppose I have a pickle file with a
> variable number of objects. How do I unpickle the objects without
> generating an EOF exception?

Hi Robert,

Has anyone addressed your question yet?

Checking for EOF in Python is not idiomatic: you can explicitely detect
the condition by using a try/except block, but you may want to rework the
code so that it doesn't need to worry about EOF under normal
circumstances.


In a pinch, you could probably do something like:

###
objects = []
try:
    while True:
        objects.append(pickle.load(srcfile))
except EOFError:
    pass
###

But one way to avoid checking explicitely for EOF to modify the way you're
pickling your objects.  Instead of keeping a variable number of objects,
it might be easier to pickle a single list that contains those objects.


Alternatively, you can first pickle an integer that tells us how many
pickled objects you'll be dumping.  That way, you'd know how many times
you'd have to load() during the unpickling.

Would that work for you?


I hope this helps!



More information about the Tutor mailing list