Graceful detection of EOF

Andrew Dalke adalke at
Thu Oct 7 18:24:51 EDT 2004

MickeyBob wrote:
> How does one detect the EOF gracefully? Assuming I have a pickle file
> containing an unknown number of objects, how can I read (i.e.,
> pickle.load()) until the EOF is encountered without generating an EOF
> exception?

Why isn't catching the exception graceful?


def load_pickle_iter(infile):
   while 1:
       yield pickle.load(infile)
     except EOFError:

for obj in load_pickle_iter(open("mydata.pickle", "rb")):
   print obj

This is well in line with the normal Python idiom,
as compared to "look before you leap".

				dalke at

More information about the Python-list mailing list