使用cPickle时遇到问题

时间:2010-02-14 00:09:52

标签: 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()    

运行两次以查看错误:

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

3 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:4)

对于每个负载,您需要打开(使用mode ='rb'),加载并关闭文件句柄。
对于每个转储,您需要打开(使用mode ='wb'),转储并关闭文件句柄。

答案 2 :(得分:1)

您已打开文件进行读写 - 即随机访问。当您最初读取文件时,将文件索引位置保留在文件末尾,因此当您稍后再写入数据时,您将附加到同一文件中。

您应该以读取模式打开文件,读取数据,关闭数据,然后以写入模式重新打开。