为什么pickle文件没有被修改?但是在我取消注释它之后它会起作用吗?
with open(PATH, "rb+") as fp:
mocks_pickle = pickle.load(fp)
mocks_pickle['aa'] = '123'
# pickle.dump(mocks_pickle, open(PATH, 'wb'))
pickle.dump(mocks_pickle, fp)
答案 0 :(得分:3)
在转储对象之前,您需要使用fp.seek(0)
搜索文件的开头。
如果您没有寻求将新的泡菜附加到文件的末尾。
当你从文件中pickle.load
时,你只得到文件中的第一个。
with open(PATH, "rb+") as fp:
mocks_pickle = pickle.load(fp)
mocks_pickle['aa'] = '123'
fp.seek(0)
pickle.dump(mocks_pickle, fp)