gpt4 book ai didi

python - 如何 pickle 和去 pickle

转载 作者:太空狗 更新时间:2023-10-30 00:06:24 25 4
gpt4 key购买 nike

import  pickle
variety = ["sweet", "box", "cat"]
shape = ["back","spear", "log"]
pickleFile = open("pickle.txt", 'w')
pickle.dump(variety, pickleFile)
pickle.dump(shape, pickleFile)
pickleFile.close()

pickleFile = open("pickle.txt", 'r')
test = pickle.load(pickleFile)
shape = pickle.load(pickleFile)

print ("variety : ", test, " shape : ", shape)
pickleFile.close()

当我运行上面的代码时,出现以下错误

line 6, in <module>
pickle.dump(variety, pickleFile)
TypeError: must be str, not bytes

而且我不确定是否可以在变量“test”中进行 unpickling或者不是因为我用变量“多样性” pickle 了

最佳答案

根据help(pickle.dump)

The file argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface.

看起来您必须以二进制模式打开您的文件。不要忘记对 loading 也做同样的事情。

import  pickle
variety = ["sweet", "box", "cat"]
shape = ["back","spear", "log"]
pickleFile = open("pickle.txt", 'wb')
pickle.dump(variety, pickleFile)
pickle.dump(shape, pickleFile)
pickleFile.close()

pickleFile = open("pickle.txt", 'rb')
test = pickle.load(pickleFile)
shape = pickle.load(pickleFile)

print ("variety : ", test, " shape : ", shape)
pickleFile.close()

结果:

variety :  ['sweet', 'box', 'cat']  shape :  ['back', 'spear', 'log']

关于python - 如何 pickle 和去 pickle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33127866/

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