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

时间:2017-09-01 14:03:54

标签: python python-3.x pickle

我正在尝试在Python 3中打开一个pickle文件,其代码在Python 2中有效但现在给我一个错误。这是代码:

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'.

3 个答案:

答案 0 :(得分:6)

使用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

答案 1 :(得分:1)

是的,Python 2和3 pickle格式之间有一些变化。如果可能的话,我建议使用Python 3再次创建pickle数据。

如果这不可能/容易,请尝试使用不同的编码设置(您尝试'utf8'吗?)或使用encoding='bytes'读取数据here,然后解码字符串在您的代码中,您可以进一步检查对象。

答案 2 :(得分:-1)

在Sublime中挖掘原始文件后,看起来文件没有被正确腌制。上面的代码完全适用于该文件的不同版本。