我正在尝试使用在Python 2中有效的代码打开一个pickle文件,但现在却出现了错误。以下是代码:
with open(file, 'r') as f:
d = pickle.load(f)
TypeError Traceback (most recent call last)
<ipython-input-25-38f711abef06> in <module>()
1 with open(file, 'r') as f:
----> 2 d = pickle.load(f)
TypeError: a bytes-like object is required, not 'str'
我在其他SO答案中看到,当使用open(file ,'rb')
时人们会遇到这个问题,而切换到open(file ,'r')
则可以解决。如果有帮助的话,我为了实验尝试了open(file ,'rb')
,但是得到了以下错误:
UnpicklingError Traceback (most recent call last)
<ipython-input-26-b77842748a06> in <module>()
1 with open(file, 'rb') as f:
----> 2 d = pickle.load(f)
UnpicklingError: invalid load key, '\x0a'.
当我使用f = open(file, 'r')
打开文件并输入f
时,我会得到以下结果:
<_io.TextIOWrapper name='D:/LargeDataSets/Enron/final_project_dataset.pkl' mode='r' encoding='cp1252'>
所以我也尝试了:
with open(file, 'rb') as f:
d = pickle.load(f, encoding='cp1252')
使用 'rb' 仍然出现了相同的错误:
UnpicklingError Traceback (most recent call last)
<ipython-input-27-959b1b0496d0> in <module>()
1 with open(file, 'rb') as f:
----> 2 d = pickle.load(f, encoding='cp1252')
UnpicklingError: invalid load key, '\x0a'.