Python3.xでエラーTypeErrorが発生します: 'str'ではなくバイトのようなオブジェクトが必要です



Python3 X Gives An Error Typeerror



Python3.xエラーTypeError:「str」ではなくバイトのようなオブジェクトが必要です

pickle.load()を呼び出すと、Python3.xでエラーが発生します



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

Python3とPython2の間の文字列の互換性の問題のため、データファイルはPython 2でシリアル化されるため、Python 3で読み取る場合は、「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')))