gpt4 book ai didi

python - 在 python 中进行 pickling 的 pickle 中

转载 作者:行者123 更新时间:2023-11-30 23:33:44 27 4
gpt4 key购买 nike

我浏览过这个网站和许多其他网站,但似乎没有人给我最简单的答案。在下面的脚本中,有 2 个不同的变量需要放入一个 pickle 中(又名“test1”和“test2”);但我完全无法加载两者中更简单的一个。没有错误消息或任何内容,并且似乎确实有一些内容正在写入pickle,但随后我关闭“程序”,重新打开它,尝试加载pickle,但“test1”的值没有改变。

第二个问题是如何将两者保存到同一个pickle中?起初,我尝试使用 allStuff 变量来存储 test1 和 test2,然后转储 allStuff...转储似乎成功,但加载确实成功。我尝试过一种变体,列出应该加载的每个文件,但这只会导致很多错误,并导致我攻击我可怜的旧键盘......

请帮忙。

import pickle

class testing():

test1 = 1000
test2 = {'Dogs' : 0, 'Cats' : 0, 'Birds' : 0, 'Mive' : 0}


def saveload():
check = int(input(' 1. Save : 2. Load : 3. Print : 4. Add'))
allStuff = testing.test1, testing.test2
saveFile = 'TestingSaveLoad.data'

if check == 1:
f = open(saveFile, 'wb')
pickle.dump(testing.test1, f)
f.close()
print()
print('Saved.')
testing.saveload()


elif check == 2:
f = open(saveFile, 'rb')
pickle.load(f)
print()
print('Loaded.')
testing.saveload()


elif check == 3:
print(allStuff)
testing.saveload()

else:
testing.test1 += 234
testing.saveload()


testing.saveload()

最佳答案

pickle.load文档说明:

Read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified therein.

所以你需要这样的东西:

testing.test1 = pickle.load(f)

但是,要保存和加载多个对象,您可以使用

# to save
pickle.dump(allStuff, f)

# to load
allStuff = pickle.load(f)
testing.test1, testing.test2 = allStuff

关于python - 在 python 中进行 pickling 的 pickle 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18596299/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com