解决python3.x报错 TypeError: a bytes-like object is required, not 'str'

python3.x报错 TypeError: a bytes-like object is required, not ‘str’

python3.x调用pickle.load()时报错

ages = pickle.load( open("practice_outliers_ages.pkl", "r") )
TypeError: a bytes-like object is required, not 'str'

是由于 Python3和Python2的字符串兼容问题,因为数据文件是在Python2下序列化的,所以使用Python3读取时,需要将‘str’转化为’bytes’。

#python2 to python3
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()



ages = pickle.load( StrToBytes(open("practice_outliers_ages.pkl", "r")))

你可能感兴趣的:(Python,常见问题)