python - 使用 cPickle 的问题

标签 python pickle

你能帮我实现这个例子吗?

如果序列化字典存在,我想加载它,修改它并再次转储它。我认为我用于打开文件的模式有问题,但我不知道正确的方法。

import os
import cPickle as pickle

if os.path.isfile('file.txt'):
    cache_file = open('file.txt', 'rwb')
    cache = pickle.load(cache_file)
else:
    cache_file = open('file.txt', 'wb')
    cache = dict.fromkeys([1,2,3])

# modifications of cache

pickle.dump(cache, cache_file)
cache_file.close()    

运行两次可以看到错误:

Traceback (most recent call last):
  File "example.py", line 11, in <module>
    pickle.dump(cache, cache_file)
IOError: [Errno 9] Bad file descriptor

最佳答案

'rwb' 不是 open() 的正确文件打开模式。试试 'r+b'

从文件中读取后,光标位于文件末尾,因此 pickle.dump(cache, cache_file) 将附加到文件(这可能不是您想要的).在 pickle.load(cache_file) 之后尝试 cache_file.seek(0)

关于python - 使用 cPickle 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259636/

相关文章:

python - 如何pickle从dict派生的python对象

python - Django 模型字段。自定义字段值 setter

python - (PyQt 和 PySide)QFileDialog.getExistingDirectory 在 Windows 上不起作用

python - 内存错误: bad allocation when Pycharm shows barely any memory use

python - 在 Pandas 中,如何读取抛出 Unpickling 错误 : invalid load key? 的 Pickle 文件

python - 使用 Python cPickle 从文件中读取数据

python - 悲怆多处理不能 pickle

python - reportlab 值错误 : Invalid color value 'initial'

python - 如何使用 wsgi 在 URL 路径中包含变量? (不是查询字符串)

javascript - Python 类 JavaScript 中的函数模拟