小编典典

为什么我在读取空文件时收到“Pickle - EOFError: Ran out of input”?

all

我在尝试使用时遇到了一个有趣的错误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

我要读取的文件是空的。我怎样才能避免出现这个错误,而是得到一个空变量?


阅读 94

收藏
2022-07-29

共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()没有做任何事情,您不需要使用;.

2022-07-29