使用cPickle时遇到问题

Jua*_*nti 1 python pickle

你能帮忙做这个例子吗?

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

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()    
Run Code Online (Sandbox Code Playgroud)

运行两次以查看错误:

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

Mes*_*ssa 5

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

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