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

  python3下使用和pickle.load时出现了错误

import pickle as Pickle
target_params = Pickle.load(open('save/target_params_py3.pkl', 'r'))
Error: 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('save/target_params_py3.pkl', 'r') as data_file:  
    data_dict = pickle.load(StrToBytes(data_file))

经过转换后,错误信息是UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

这是因为,pickle(除了最早的版本外)是二进制格式的,所以你应该带 'b' 标志打开文件

target_params = Pickle.load(open('save/target_params_py3.pkl', 'rb'))


猜你喜欢

转载自blog.csdn.net/u010899985/article/details/80827630
今日推荐