python - 为什么我在读取空文件时得到 "Pickle - EOFError: Ran out of input"?

标签 python file pickle

我在尝试使用 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

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

最佳答案

这里的大多数答案都涉及如何管理 EOFError 异常,如果您不确定 pickle 对象是否为空,这非常方便。

但是,如果您对 pickle 文件为空感到惊讶,可能是因为您通过“wb”或其他可能覆盖文件的模式打开了文件名。

例如:

filename = 'cd.pkl'
with open(filename, 'wb') as f:
    classification_dict = pickle.load(f)

这将覆盖 pickle 文件。您可能在使用前错误地这样做了:

...
open(filename, 'rb') as f:

然后得到 EOFError 因为前面的代码块覆盖了 cd.pkl 文件。

在 Jupyter 或控制台 (Spyder) 中工作时,我通常会在读/写代码上编写一个包装器,然后调用该包装器。这避免了常见的读写错误,并且如果您要通过您的 travails 多次读取同一个文件,可以节省一些时间

关于python - 为什么我在读取空文件时得到 "Pickle - EOFError: Ran out of input"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24791987/

相关文章:

python - 不能在 Django 中 pickle 字典

python - python中带有随机点的二维插值

Python Groupby 字符串的一部分

c - 使用 fputs() 将整数写入文件

python - unpickling 命名元组时出错

python - 在 Python 中使用 pickle 高效地访问字典中的项目

python - 在 websocket 握手中发送自定义 header

python - 访问字典,用字典中的信息替换用户输入中的项目

php - 什么是 php 中的流和流包装器

java - 如何在java中打开另一个目录中的文件?