我得到一个有趣的错误,而试图使用Unpickler.load(),这是源代码:

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

下面是回溯:

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

我正在读取的文件是空的。 我如何避免得到这个错误,并得到一个空变量代替?


当前回答

也有同样的问题。原来,当我写入pickle文件时,我没有使用file.close()。插入这一行,错误就不再存在了。

其他回答

这里的大多数答案都涉及了如何管理EOFError异常,如果您不确定pickle对象是否为空,这非常方便。

然而,如果您惊讶于pickle文件是空的,这可能是因为您通过'wb'或其他可能覆盖该文件的模式打开了文件名。

例如:

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

这将覆盖pickle文件。你可能在使用之前错误地这样做了:

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

然后得到EOFError,因为前面的代码块覆盖了cd.pkl文件。

当在Jupyter或在控制台(Spyder)中工作时,我通常在读写代码上编写包装器,然后调用包装器。这避免了常见的读写错误,如果要多次读取同一个文件,还节省了一些时间

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

您可以捕获该异常并从那里返回您想要的任何内容。

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

我会先检查文件是否为空:

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()

同样,open(target, 'a').close()在你的代码中什么也不做,你不需要使用;。

也有同样的问题。原来,当我写入pickle文件时,我没有使用file.close()。插入这一行,错误就不再存在了。