使用pickle.dump-TypeError:必须为str,而不是字节


242

我正在使用python3.3,并且在尝试腌制一个简单的字典时遇到一个神秘的错误。

这是代码:

import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')

def storvars(vdict):      
    f = open('varstor.txt','w')
    pickle.dump(vdict,f,)
    f.close()
    return

mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)

我得到:

Traceback (most recent call last):
  File "C:/Python26/test18.py", line 31, in <module>
    storvars(mydict)
  File "C:/Python26/test18.py", line 14, in storvars
    pickle.dump(vdict,f,)
TypeError: must be str, not bytes

Answers:


404

需要以二进制模式打开输出文件:

f = open('varstor.txt','w')

需要是:

f = open('varstor.txt','wb')

22
遇到完全相同的问题后,我看到了针对和的文档中提到了“二进制”读/写的需求。在两个地方,仅在函数说明的中间提到了这一点。有人应该更清楚地说明这一点。pickle.dump()pickle.load()
马修

9
我向Python项目提交#24159。在这种情况和类似情况下,也许可以采取一些措施来改善体验。
杰森·库姆斯

1
本文未提及使用wb模式,它出现在搜索结果的顶部,并于2019年撰写:Thoughtco.com/using-pickle-to-save-objects-2813661
deltaray

22

只是有同样的问题。在Python 3中,必须指定二进制模式'wb','rb',而在Python 2x中则不需要。当您遵循基于Python 2x的教程时,这就是您在这里的原因。

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.