溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么用python3讀取python2的pickle數(shù)據(jù)方式

發(fā)布時間:2021-04-25 14:22:07 來源:億速云 閱讀:208 作者:小新 欄目:開發(fā)技術

這篇文章主要介紹了怎么用python3讀取python2的pickle數(shù)據(jù)方式,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

python有哪些常用庫

python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。

問題一:TypeError: a bytes-like object is required, not 'str'

解決:該問題屬于Python3和Python2的字符串兼容問題,數(shù)據(jù)文件是在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數(shù)據(jù)方式”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI