为什么我会收到"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:\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
我尝试读取的文件为空. 如何避免出现此错误,而是获取一个空变量?
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屋!
查看全文