TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str' [英] TypeError: a bytes-like object is required, not 'str' when opening Python 2 Pickle file in Python 3

查看:96
本文介绍了TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用在Python 2中可以运行的代码在Python 3中打开一个pickle文件,但是现在却给我一个错误.这是代码:

I am trying to open a pickle file in Python 3 with code that worked in Python 2 but is now giving me an error. Here is the code:

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')只是为了进行实验,并收到以下错误:

I saw on other SO answers that people had this problem when using open(file ,'rb') and switching to open(file ,'r') fixed it. If this helps, I tried open(file ,'rb') just to experiment and got the following error:

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时,我得到:

When I open the file with f = open(file, 'r') and the enter f I get:

<_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'相同的错误:

and got the same error as with using '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'.

推荐答案

在Sublime中浏览原始文件后,似乎未正确地对文件进行酸洗.上面的代码可以完美地在该文件的其他版本上使用.

After digging through the raw file in Sublime, it looks like the file was not correctly pickled. The above code works perfectly on a different version of that file.

这篇关于TypeError:需要一个类似字节的对象,而在Python 3中打开Python 2 Pickle文件时不是'str'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆