如何酸洗和去角质

时间:2015-10-14 14:18:25

标签: python python-3.x pickle

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

并且我不确定是否在变量&#39;测试&#39;将是可能的 或者不是因为我使用变量&#39;

进行了腌制

2 个答案:

答案 0 :(得分:4)

根据help(pickle.dump)

  

文件参数必须具有接受单个的write()方法   bytes参数。因此它可以是为二进制打开的文件对象   写入,io.BytesIO实例或任何其他自定义对象   这个界面。

看起来您必须以二进制模式打开文件。不要忘记对load也这样做。

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

答案 1 :(得分:0)

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

腌制文件的正确文件扩展名为&#39; .pkl&#39;。该文件还必须以二进制模式写入和读取。

我的建议是将文件扩展名更改为&#39; .pkl&#39;然后使用两个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()