python--json與pickle序列化

來源:互聯網
上載者:User

標籤:語言   info   hello   json   功能   def   int   反序   --   

json & pickle 模組

用於序列化的兩個模組

  • json,用於字串 和 python資料類型間進行轉換
  • pickle,用於python特有的類型 和 python的資料類型間進行轉換

Json模組提供了四個功能:dumps、dump、loads、load

pickle模組提供了四個功能:dumps、dump、loads、load

#json只能處理簡單的資料類型 可以和其它語言進行互動#json不同平台資料處理進行互動#用json實現存入資料和讀取資料#序列化 存入資料info = {    ‘name‘:‘python‘,    ‘age‘:30}import jsonf = open("test",‘w‘)# f.write(str(info)) #str變為字串f.write(json.dumps(info))#還原序列化 讀取資料import jsonf = open("test",‘r‘)data = json.loads(f.read())print(data["age"])#pickle 處理複雜的 可以序列化所有的資料類型#序列化import pickledef saihi(name):    print("hello",name)info = {    ‘name‘:‘python‘,    ‘age‘:30,    ‘func‘:saihi}f = open("test",‘wb‘)# f.write(str(info)) #str變為字串f.write(pickle.dumps(info))#還原序列化import pickledef saihi(name):    print("hello",name)    print("hello1",name)f = open("test",‘rb‘)data = pickle.loads(f.read())print(data["func"]("python"))#pickle 中dump 同dumps實現效果一樣 import pickledef saihi(name):    print("hello",name)info = {    ‘name‘:‘python‘,    ‘age‘:30,    ‘func‘:saihi}f = open("test",‘wb‘)pickle.dump(info,f)f.close()#pickle中loadimport pickledef saihi(name):    print("hello",name)    print("hello1",name)f = open("test",‘rb‘)data = pickle.load(f)#序列化 用json dump兩次import jsoninfo = {    ‘name‘:‘python‘,    ‘age‘:30,}f = open("test",‘w‘)f.write(json.dumps(info))info[‘age‘] = 22f.write(json.dumps(info))f.close()#註:只dump一次load一次 如虛擬機器中快照 

 

python--json與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.