你能帮我搞定这张旧版吗?在
我想加载一个序列化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()
运行两次以查看错误:
^{pr2}$
您已打开文件进行读写-即随机访问。当您最初读取文件时,您将文件索引位置保留在文件末尾,因此当您稍后将数据写回时,您将附加到同一个文件中。在
您应该以读模式打开文件,读取数据,关闭它,然后以写入模式重新打开。在
'rwb'
不是open()
的正确文件打开模式。尝试'r+b'
。在从文件中读取后,光标位于文件末尾,因此之后尝试
pickle.dump(cache, cache_file)
将追加到文件中(这可能不是您想要的)。在^{cache_file.seek(0)
。在对于每次加载,您需要打开(使用mode='rb')、加载并关闭文件句柄。
对于每个转储,需要打开(with mode='wb')、转储并关闭文件句柄。在
相关问题 更多 >
编程相关推荐