如何腌制和取消包装

2024-05-16 19:47:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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”中取消勾选是否可行 或者不是因为我加入了变化多端的“变种”


Tags: testimporttxtboxclosebackloadopen
2条回答

您的问题是您正试图将pickled对象写入文本文件。这就像试图用MS-word编写数据库一样。

pickled文件的正确文件扩展名为“.pkl”。文件还必须以二进制模式写入和读取。

我的建议是将文件扩展名改为“.pkl”,然后使用两个with循环来整理代码。对加载和写入的更正非常简单,只需将'w'更改为'wb',结果如下:

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

with open("pickle.pkl", 'rb') as pickleFile:
    test = pickle.load(pickleFile)
    shape = pickle.load(pickleFile)

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

根据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']

相关问题 更多 >