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