[Tutor] sensing EOF in Python 3.1

Steven D'Aprano steve at pearwood.info
Wed Nov 23 23:02:04 CET 2011


Cranky Frankie wrote:
> I'm reading in a pickled file. The program works but I'm having
> trouble sensing end of file. Here's the program:
[...]
> Traceback (most recent call last):
>   File "D:\MyDocs\Python\pickle_in.py", line 21, in <module>
>     read_file = pickle.load(pickle_file)        # read the next record
> in the input file
>   File "D:\Python31\lib\pickle.py", line 1365, in load
>     encoding=encoding, errors=errors).load()
> EOFError

Seems to me that you have successfully found the end of file.

I'm not be facetious here. "Easier to ask forgiveness afterwards than 
permission before hand" is generally (but not necessarily always) the 
preferred way of coding things in Python. So instead of trying to 
predict the end of file ahead of time:

while some_hard_to_calculate_condition():
     do_stuff_with_pickle()

you can catch the error instead:

try:
     while True:  # Loop forever, until interrupted
         do_stuff_with_pickle()
except EOFError:
     # no more pickles, so we must be done
     pass



-- 
Steven



More information about the Tutor mailing list