我在尝试使用 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
我要读取的文件是空的。 我怎样才能避免出现这个错误,而是得到一个空变量?
最佳答案
这里的大多数答案都涉及如何管理 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) 中工作时,我通常会在读/写代码上编写一个包装器,然后调用该包装器。这避免了常见的读写错误,并且如果您要通过您的 travails 多次读取同一个文件,可以节省一些时间
关于python - 为什么我在读取空文件时得到 "Pickle - EOFError: Ran out of input"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791987/