【问题标题】:how can load all dumped appended dict in python pickle?如何在 python pickle 中加载所有转储附加字典?
【发布时间】:2021-10-28 21:30:53
【问题描述】:

我已经解决了泡菜的练习,我先用泡菜转储一个字典,然后需要转储另一个字典并将其附加到以前的转储文件中,但是当我想加载文件并将两个字典放在一起时,只需取回先dump了dict怎么解决这个问题?

with open('test.ts', 'ab') as f:
    pickle.dump({'first': 1}, f)

with open('test.ts', 'ab') as f:
    pickle.dump({'second': 2}, f)

with open('test.ts', 'rb') as f:
    t = pickle.load(f)

>>>print(t)

>>>{'first': 1} #need to get dictionaries like this {'first': 1}{'second': 2}

【问题讨论】:

  • 不是您问题的真正答案。但是你能把(dict1, dict2)作为一个单独的项目转储,然后dict1, dict2 = pickle.load(f)吗?

标签: python python-3.x pickle


【解决方案1】:

您需要多次使用pickle.load 从文件中读取:

t1 = pickle.load(f)
t2 = pickle.load(f)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多