Python 使用 pickle.dump - TypeError: 必须是 str,而不是字节
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13906623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using pickle.dump - TypeError: must be str, not bytes
提问by John Rowland
I'm using python3.3 and I'm having a cryptic error when trying to pickle a simple dictionary.
我正在使用 python3.3 并且在尝试pickle一个简单的字典时遇到了一个神秘的错误。
Here is the code:
这是代码:
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)
and I get:
我得到:
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
回答by Jon Clements
The output file needs to be opened in binary mode:
输出文件需要以二进制模式打开:
f = open('varstor.txt','w')
needs to be:
需要是:
f = open('varstor.txt','wb')
回答by Well Smith
Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.
刚刚有同样的问题。在 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("------------")

