您的位置:首页 > 移动开发 > Objective-C

解决python3的pickle.load错误:a bytes-like object is required, not 'str'

2017-12-12 12:38 961 查看
最近在python3下使用pickle.load时出现了错误。

import pickle

with open('final_project_dataset.pkl', 'r') as data_file:
data_dict = pickle.load(data_file)


错误信息如下:

data_dict = pickle.load(data_file)

TypeError: a bytes-like object is required, not 'str'


经过几番查找,发现是Python3和Python2的字符串兼容问题,因为数据文件是在Python2下序列化的,所以使用Python3读取时,需要将‘str’转化为'bytes'。

class StrToBytes:
def __init__(self, fileobj):
self.fileobj = fileobj
def read(self, size):
return self.fileobj.read(size).encode()
def readline(self, size=-1):
return self.fileobj.readline(size).encode()

with open('final_project_dataset.pkl', 'r') as data_file:
data_dict = pickle.load(StrToBytes(data_file))
经过这样一个转化后,就可以正确读取数据了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐