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'))
本文介绍了解决Python3环境下使用pickle加载Python2中序列化数据遇到的问题,包括如何处理字符串兼容性和二进制文件读取错误。

2705

被折叠的 条评论
为什么被折叠?



