一尘不染

为什么在读取一个空文件时出现“ Pickle-EOFError:Ran out of input”的问题?

python

尝试使用时出现一个有趣的错误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

我尝试读取的文件为空。如何避免出现此错误,而是获取一个空变量?


阅读 192

收藏
2020-12-20

共1个答案

一尘不染

我先检查文件是否为空:

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()在您的代码中什么也没做,您不需要使用;

2020-12-20