Python之pickle

來源:互聯網
上載者:User

標籤:反序   pickle   常用函數   span   file   prot   open   開啟   data   

Pickle模組可以序列化對象並儲存到磁碟中,並在需要的時候讀取出來,任何對象都可以執行序列化操作。在機器學習中,我們常常需要把訓練好的模型儲存起來,這樣在進行決策時直接將模型獨處,而不需要重新訓練模型,這樣就大大節約了時間。
pickle模組常用函數
dump(obj,file,[,protocol]) 將obj對象序列化存入已經開啟的file中
load(file) 將file中的對象序列化讀出
dumps(obj,[,protocol]) 將obj對象序列化為string形式,而不是存入檔案中
loads(string) 從string中讀出序列化前的obj對象
樣本
#coding=utf-8import pickledatalist = [[1, 1, ‘yes‘],             [1, 1, ‘yes‘],             [1, 0, ‘no‘],             [0, 1, ‘no‘],             [0, 1, ‘no‘]]             datadict = { 0: [1, 2, 3, 4],              1: (‘a‘, ‘b‘),              2: {‘c‘:‘yes‘,‘d‘:‘no‘}}  with open("pickle_test.txt","wb") as writefp:    pickle.dump(datalist, writefp)    pickle.dump(datadict, writefp)  with open("pickle_test.txt", "rb") as readfp:    data1 = pickle.load(readfp)    data2 = pickle.load(readfp)    print (data1)    print (data2)p = pickle.dumps(datalist)  print( pickle.loads(p) )  p = pickle.dumps(datadict)  print( pickle.loads(p) ) 

  >>> [[1, 1, ‘yes‘], [1, 1, ‘yes‘], [1, 0, ‘no‘], [0, 1, ‘no‘], [0, 1, ‘no‘]]
  >>> {0: [1, 2, 3, 4], 1: (‘a‘, ‘b‘), 2: {‘c‘: ‘yes‘, ‘d‘: ‘no‘}}
  >>> [[1, 1, ‘yes‘], [1, 1, ‘yes‘], [1, 0, ‘no‘], [0, 1, ‘no‘], [0, 1, ‘no‘]]
  >>> {0: [1, 2, 3, 4], 1: (‘a‘, ‘b‘), 2: {‘c‘: ‘yes‘, ‘d‘: ‘no‘}}

  dump和load相比dumps和loads還有另外一種能力:dump()函數能一個接著一個的將幾個對象序列化儲存到同一個檔案中,隨後調用load()來以同樣的順序還原序列化讀出這些對象

Python之pickle

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.