用python3读取python2的pickle数据方式

yipeiwu_com6年前Python基础

问题一: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)

以上这篇用python3读取python2的pickle数据方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现随机漫步算法

本文实例为大家分享了python实现随机漫步的具体代码,供大家参考,具体内容如下 编写randomwalk类 from random import choice class ra...

pandas的object对象转时间对象的方法

如下所示: df = pd.read_table('G:/tc/dataset/user_view.txt', sep=",")#读取文件 df.columns = ["a", "b...

总结python实现父类调用两种方法的不同

总结python实现父类调用两种方法的不同

python中有两种方法可以调用父类的方法: super(Child, self).method(args)  Parent.method(self, args) 我用其中的一...

Python实现加载及解析properties配置文件的方法

本文实例讲述了Python实现加载及解析properties配置文件的方法。分享给大家供大家参考,具体如下: 这里参考前面一篇:/post/137393.htm 我们都是在java里面遇...

Python Paramiko模块的使用实际案例

本文研究的主要是Python Paramiko模块的使用的实例,具体如下。 Windows下有很多非常好的SSH客户端,比如Putty。在python的世界里,你可以使用原始套接字和一些...