我在尝试使用 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
我要读取的文件是空的。我怎样才能避免出现这个错误,而是得到一个空变量?
原文由 Magix 发布,翻译遵循 CC BY-SA 4.0 许可协议
我会先检查文件是否为空:
此外
open(target, 'a').close()
在您的代码中什么也不做,您不需要使用;
。