Search code examples
pythonfilepickle

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


I am getting an interesting error while trying to use Unpickler.load(), here is the source code:

open(target, 'a').close()
scores = {};
with open(target, "rb") as file:
    unpickler = pickle.Unpickler(file);
    scores = unpickler.load();
    if not isinstance(scores, dict):
        scores = {};

Here is the traceback:

Traceback (most recent call last):
File "G:\python\pendu\user_test.py", line 3, in <module>:
    save_user_points("Magix", 30);
File "G:\python\pendu\user.py", line 22, in save_user_points:
    scores = unpickler.load();
EOFError: Ran out of input

The file I am trying to read is empty. How can I avoid getting this error, and get an empty variable instead?


Solution

  • I would check that the file is not empty first:

    import os
    
    scores = {} # scores is an empty dict already
    
    if 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 ;.