我正在尝试使用在 Python 2 中工作的代码在 Python 3 中打开一个泡菜文件,但现在给我一个错误。这是代码:
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'.
原文由 jss367 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Sublime 中挖掘原始文件后,看起来文件没有正确 pickle。上面的代码在该文件的不同版本上完美运行。