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

来源:互联网 发布:免费期刊文献资源 知乎 编辑:程序博客网 时间:2024/05/16 20:31

最近在python3下使用pickle.load时出现了错误。

import picklewith 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))
经过这样一个转化后,就可以正确读取数据了。

阅读全文
0 0
原创粉丝点击