Graceful detection of EOF
Jeremy Jones
zanesdad at bellsouth.net
Thu Oct 7 18:58:05 EDT 2004
Andrew Dalke wrote:
> 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
So, what you're saying is that the Python way, in contradistinction to
"look before you leap", is "land in it, then wipe it off?" Can we get
that in the Zen of Python? :-)
Seriously, this is beautiful. I understand generators, but haven't
become accustomed to using them yet. That is just beautiful, which _is_
Zen.
Jeremy Jones
More information about the Python-list
mailing list