用python3读取python2的pickle数据方式

作者:Sandwichsauce 时间:2023-06-05 09:45:48 

问题一:TypeError: a bytes-like object is required, not 'str'

解决:该问题属于Python3和Python2的字符串兼容问题,数据文件是在Python2下序列化的,使用Python3读取时,需要将‘str'转化为'bytes'。


picklefile=open('XXX.pkl','r')

class StrToBytes:
 def __init__(self, fileobj):
   self.fileobj = fileobj
 def read(self, size):
   return self.fileobj.read(size).encode()
 def readline(self, size=-1):
   return self.fileobj.readline(size).encode()

data=pickle.load(StrToBytes(picklefile))

问题二:UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 44: ordinal not in range(128)

解决:加上encoding编码方式


pickle.load(StrToBytes(data_file),encoding='iso-8859-1')

附上完整的读取代码:


import pickle
class StrToBytes:
 def __init__(self, fileobj):
   self.fileobj = fileobj
 def read(self, size):
   return self.fileobj.read(size).encode()
 def readline(self, size=-1):
   return self.fileobj.readline(size).encode()

read = open('XXX.pkl', 'r')
data = pickle.load(StrToBytes(read),encoding='iso-8859-1')

print(data)

来源:https://blog.csdn.net/Sandwichsauce/article/details/88638454

标签:python3,python2,pickle
0
投稿

猜你喜欢

  • Python利用第三方模块实现压缩css文件

    2023-04-28 07:21:02
  • python的open函数使用案例代码

    2022-01-20 16:41:30
  • Oracle Instr函数实例讲解

    2024-01-14 18:05:32
  • TensorFlow人工智能学习数据类型信息及转换

    2022-11-02 09:12:55
  • Google中国新首页风格再度变脸

    2008-10-27 13:37:00
  • 详解mybatis-plus实体类中字段和数据库中字段名不对应解决办法

    2024-01-26 23:59:19
  • PHP的mysqli_thread_id()函数讲解

    2023-06-13 10:09:43
  • asp如何用Access加密页面?

    2010-06-10 18:41:00
  • python里dict变成list实例方法

    2021-12-22 18:52:43
  • python用quad、dblquad实现一维二维积分的实例详解

    2022-02-17 05:32:51
  • python3 xpath和requests应用详解

    2022-10-13 18:24:36
  • 简单了解Django应用app及分布式路由

    2023-08-30 19:29:47
  • xhEditor 免费的国产HTML在线编辑器

    2022-05-25 23:05:32
  • Python操作Redis之设置key的过期时间实例代码

    2022-02-11 06:13:05
  • 详解git merge 与 git rebase的区别

    2023-04-07 20:02:49
  • vue实现列表倒计时

    2024-04-28 09:30:36
  • 在SQL Server中处理空值时涉及的三个问题

    2009-02-05 15:30:00
  • pyEcharts安装及详细使用指南(最新)

    2022-01-30 04:14:21
  • 如何使用Python 打印各种三角形

    2023-10-27 00:12:48
  • Python机器学习算法库scikit-learn学习之决策树实现方法详解

    2023-07-26 20:44:28
  • asp之家 网络编程 m.aspxhome.com