Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? Why do I get "Pickle - EOFError: Ran out of input" reading an empty file? python python

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?


Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.

However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.

for example:

filename = 'cd.pkl'with open(filename, 'wb') as f:    classification_dict = pickle.load(f)

This will over-write the pickled file. You might have done this by mistake before using:

...open(filename, 'rb') as f:

And then got the EOFError because the previous block of code over-wrote the cd.pkl file.

When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails


I would check that the file is not empty first:

import osscores = {} # scores is an empty dict alreadyif os.path.getsize(target) > 0:          with open(target, "rb") as f:        unpickler = pickle.Unpickler(f)        # if file is not empty scores will be equal        # to the value unpickled        scores = unpickler.load()

Also open(target, 'a').close() is doing nothing in your code and you don't need to use ;.


It is very likely that the pickled file is empty.

It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.

For example the following writes a pickle file:

pickle.dump(df,open('df.p','wb'))

And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:

df=pickle.load(open('df.p','wb'))

The correct syntax is

df=pickle.load(open('df.p','rb'))