【发布时间】:2014-09-07 15:25:42
【问题描述】:
我在尝试使用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
我要读取的文件是空的。 我怎样才能避免出现这个错误,而是得到一个空变量?
【问题讨论】:
-
不要关闭文件
-
第一行
open(...).close()这里是为了保证文件存在 -
为什么不直接做
os.path.isfile(target)?