解决python3的pickle.load错误:a bytes-like object is required, not 'str'
2017-12-12 12:38
956 查看
最近在python3下使用pickle.load时出现了错误。
错误信息如下:
经过几番查找,发现是Python3和Python2的字符串兼容问题,因为数据文件是在Python2下序列化的,所以使用Python3读取时,需要将‘str’转化为'bytes'。
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))经过这样一个转化后,就可以正确读取数据了。
相关文章推荐
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- python write()参数错误,导致报错TypeError: a bytes-like object is required, not 'str'
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- python3 TypeError: a bytes-like object is required, not 'str'
- Python中“a bytes-like object is required, not 'str'”的问题
- Python学习中出现TpyeErrora bytes-like object is required, not 'str'
- python3 TypeError: a bytes-like object is required, not 'str'
- Python 3.x Error:TypeError: a bytes-like object is required, not 'str'
- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file
- python socket send 函数 报错:TypeError: a bytes-like object is required, not 'str'
- python中Base64编码和解码:TypeError: a bytes-like object is required, not 'str'
- Python 3.x: TypeError: a bytes-like object is required, not 'str'
- python3.5 模拟UDP客户端发送数据报文,报错:TypeError: a bytes-like object is required, not 'str'
- Python中3+版本运行2+版本程序出现TypeError: a bytes-like object is required, not 'str'之读取PDF中的图片
- 【Python】TypeError: a bytes-like object is required, not 'str'解决
- python3 套接字异常(a byte-like object is required not str)
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- TypeError:a bytes-like object is requeired ,not 'int'(使用python3编写出现的错误)
- python3 套接字异常(a byte-like object is required not str)
- 【Python】TypeError: a bytes-like object is required, not 'str'解决