用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设计】。

相关文章

使用TensorFlow实现简单线性回归模型

使用TensorFlow实现简单线性回归模型

本文使用TensorFlow实现最简单的线性回归模型,供大家参考,具体内容如下 线性拟合y=2.7x+0.6,代码如下: import tensorflow as tf import...

基于python yield机制的异步操作同步化编程模型

本文总结下如何在编写python代码时对异步操作进行同步化模拟,从而提高代码的可读性和可扩展性。      游戏引擎一般都采用分布式框架,通过一定...

python下的opencv画矩形和文字注释的实现方法

画矩形 函数调用:cv2.rectangle(img,pt1,pt2,color,thickness,line_type,shift) img: 图像. pt1: 矩形的一个顶点。 pt...

详解python中Numpy的属性与创建矩阵

ndarray.ndim:维度 ndarray.shape:形状 ndarray.size:元素个数 ndarray.dtype:元素数据类型 ndarray.itemsize:字节大小...

python浪漫表白源码

python浪漫表白源码

要知道我们程序猿也是需要浪漫的,小博我之前在网上搜寻了很多代码,确发现好多都不是最新的,所以自己就整理了一下代码,现在与广大博友们分享下 我们需要用到的包 使用pip install...