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

jss*_*367 6 python pickle python-3.x

我试图在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'
Run Code Online (Sandbox Code Playgroud)

我在其他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'.
Run Code Online (Sandbox Code Playgroud)

当我打开文件f = open(file, 'r')和输入f我得到:

<_io.TextIOWrapper name='D:/LargeDataSets/Enron/final_project_dataset.pkl' mode='r' encoding='cp1252'>
Run Code Online (Sandbox Code Playgroud)

所以我也尝试过:

with open(file, 'rb') as f:
    d = pickle.load(f, encoding='cp1252')
Run Code Online (Sandbox Code Playgroud)

并得到与使用'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'.
Run Code Online (Sandbox Code Playgroud)

Sre*_*A R 9

使用encoding = bytes加载的说明.

假设您有一个字典可以在Python2中进行腌制

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

在Python3中取消选择

with open('pickledObj.pkl', 'rb') as f:
        data_dict = pickle.load(f, encoding='bytes')
Run Code Online (Sandbox Code Playgroud)

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

data_dict['key1'] #result in KeyError

data_dict[b'key1'] #gives value1
Run Code Online (Sandbox Code Playgroud)

或使用

data_dict['key1'.encode('utf-8')] #gives value1
Run Code Online (Sandbox Code Playgroud)


jss*_*367 -1

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