为什么我得到“Pickle - EOFError: Ran out of input"?读取空文件? [英] Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?
本文介绍了为什么我得到“Pickle - EOFError: Ran out of input"?读取空文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在尝试使用 Unpickler.load()
时遇到一个有趣的错误,这是源代码:
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 = {};
这是回溯:
Traceback (most recent call last):
File "G:pythonpenduuser_test.py", line 3, in <module>:
save_user_points("Magix", 30);
File "G:pythonpenduuser.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?
推荐答案
我会先检查文件是否为空:
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()
还有 open(target, 'a').close()
在你的代码中什么都不做,你不需要使用 ;
.
Also open(target, 'a').close()
is doing nothing in your code and you don't need to use ;
.
这篇关于为什么我得到“Pickle - EOFError: Ran out of input"?读取空文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文