使用 pickle.dump – TypeError:必须是 str,而不是 bytes
- 2025-03-05 09:14:00
- admin 原创
- 83
问题描述:
我正在使用 python3.3,在尝试 pickle 一个简单的字典时出现了一个神秘的错误。
以下是代码:
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
解决方案 1:
输出文件需要以二进制模式打开:
f = open('varstor.txt','w')
需要:
f = open('varstor.txt','wb')
解决方案 2:
刚刚遇到了同样的问题。在 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("------------")
解决方案 3:
pickle 使用二进制协议,因此只接受二进制文件。正如文档第一句话所述,“pickle 模块实现了用于序列化和反序列化的二进制协议”。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD