为什么 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)

最佳答案

在转储对象之前,您需要使用fp.seek(0)搜索文件的开头。

如果不查找,则将新的 pickle 添加到文件末尾。
当您从文件中获取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)

关于python - 酱菜倾销不适用于rb +,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39488237/

10-15 05:49