Graceful detection of EOF
Andrew Dalke
adalke at mindspring.com
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?
# UNTESTED CODE
def load_pickle_iter(infile):
while 1:
try:
yield pickle.load(infile)
except EOFError:
break
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".
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list