1

你能帮我做这个例子吗?

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

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
4

3 回答 3

5

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

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

于 2010-02-14T00:11:54.540 回答
4

For each load, you need to open(with mode='rb'), load, and close the file handle.
For each dump, you need to open(with mode='wb'), dump, and close the file handle.

于 2010-02-14T00:19:07.803 回答
1

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

You should open the file in read mode, read the data, close it, then reopen in write mode.

于 2010-02-14T00:18:48.343 回答