TypeError:在 Python 3 中打开 Python 2 Pickle 文件时,需要类似字节的对象,而不是“str”

新手上路,请多包涵

我正在尝试使用在 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 许可协议

阅读 828
2 个回答

在 Sublime 中挖掘原始文件后,看起来文件没有正确 pickle。上面的代码在该文件的不同版本上完美运行。

原文由 jss367 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 encoding = bytes 加载的说明。

假设你有一本要在 Python2 中腌制的字典

data_dict= {'key1': value1, 'key2': value2}
with open('pickledObj.pkl', 'wb') as outfile:
  pickle.dump(data_dict, outfile)

在 Python3 中解包

with open('pickledObj.pkl', 'rb') as f:
        data_dict = pickle.load(f, encoding='bytes')

注意:字典的键不再是字符串。它们是字节。

 data_dict['key1'] #result in KeyError

data_dict[b'key1'] #gives value1

或使用

data_dict['key1'.encode('utf-8')] #gives value1

原文由 Sreeragh A R 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题