python序列化_json,pickle,shelve模組

來源:互聯網
上載者:User

標籤:load   name   支援   shel   .com   mes   str   byte   開啟   

序列化

序列化是指把記憶體裡的資料類型轉變成字串,以使其能儲存到硬碟或通過網路傳輸到遠程,因為硬碟或網路傳輸時只能接受bytes

  • 把記憶體資料 轉成字元,叫序列化
  • 把字元 轉成記憶體資料,叫還原序列化
模組 jsonjson.dumps() 序列化一個對象
import jsondata = {    ‘roles‘:[        {‘role‘:‘monster‘,‘type‘:‘pig‘,‘life‘:50},        {‘role‘:‘hero‘,‘type‘:‘關羽‘,‘life‘:80},    ]}d = json.dumps(data) #轉成字串print(type(d))print(d)

列印結果:

<class ‘str‘>{"roles": [{"role": "monster", "type": "pig", "life": 50}, {"role": "hero", "type": "\u5173\u7fbd", "life": 80}]}
json.lodads() 從一個對象載入資料
import jsondata = {    ‘roles‘:[        {‘role‘:‘monster‘,‘type‘:‘pig‘,‘life‘:50},        {‘role‘:‘hero‘,‘type‘:‘關羽‘,‘life‘:80},    ]}d = json.dumps(data) #僅轉成字串d2 = json.loads(d)print(type(d2),d2) #<class ‘dict‘>#{‘roles‘: [{‘role‘: ‘monster‘, ‘type‘: ‘pig‘, ‘life‘: 50}, {‘role‘: ‘hero‘, ‘type‘: ‘關羽‘, ‘life‘: 80}]}
json.dump() 將一個對象序列化存入檔案
import jsondata = {    ‘roles‘:[        {‘role‘:‘monster‘,‘type‘:‘pig‘,‘life‘:50},        {‘role‘:‘hero‘,‘type‘:‘關羽‘,‘life‘:80},    ]}f = open(‘test.json‘,mode=‘w‘)json.dump(data, f) #轉成字元並寫入檔案

結果:會將 data中的資料寫入檔案

json.load() 從一個開啟的檔案控制代碼載入資料
import jsonf = open(‘test.json‘,‘r‘)data = json.load(f)print(data[‘roles‘])

列印:

[{‘role‘: ‘monster‘, ‘type‘: ‘pig‘, ‘life‘: 50}, {‘role‘: ‘hero‘, ‘type‘: ‘關羽‘, ‘life‘: 80}]
import jsonf = open(‘json_file.json‘,‘w‘,encoding=‘utf-8‘)data1 = {‘name‘:‘nurato‘,‘skill‘:‘螺旋丸‘}data2 = [1,2,3,‘sunshine‘]json.dump(data1, f)json.dump(data2, f)

結果:

說明: 可以dump多次資料並寫入檔案

我們現在json.load 一下

f = open(‘json_file.json‘,‘r‘,encoding=‘utf-8‘)json.load(f)# 程式報錯:json.decoder.JSONDecodeError

只load 一次,並且json格式有問題,會報錯

------------------------------------------------分割線------------------------------------------------

模組pickle
import pickledata1 = {‘name‘:‘nurato‘,‘skill‘:‘螺旋丸‘}f = open(‘data.pkl‘,‘wb‘)pickle.dump(data1,f)

結果:建立了一個 名為 data.pkl 的檔案

import picklef = open(‘data.pkl‘,‘rb‘)d = pickle.load(f)print(type(d))print(d)#<class ‘dict‘>#{‘name‘: ‘nurato‘, ‘skill‘: ‘螺旋丸‘}
關於json 和 pickle

JSON:

優點:跨語言、體積小

缺點:只能支援int\str\list\tuple\dict

Pickle:

優點:專為python設計,支援python所有的資料類型

缺點:只能在python中使用,儲存資料占空間大

---------------------------------------分割線-------------------------------------------

序列化 shelve 模組
import shelvef = shelve.open(‘shelve_test‘) #開啟一個檔案names = [‘python‘, ‘html‘, ‘java‘]info = {‘name‘: ‘jack‘, ‘age‘: 25}f[‘names‘] = namesf[‘info_dic‘] = infof.close()

結果:會建立 shelve_test 檔案

import shelvef = shelve.open(‘shelve_test‘) #開啟一個檔案print(list(f.keys()))  #[‘names‘, ‘info_dic‘]print(list(f.items())) #[(‘names‘, [‘python‘, ‘html‘, ‘java‘]), (‘info_dic‘, {‘name‘: ‘jack‘, ‘age‘: 25})]print(f.get(‘names‘)) #[‘python‘, ‘html‘, ‘java‘]print(f.get(‘info_dic‘)) #{‘name‘: ‘jack‘, ‘age‘: 25}

增加內容:

import shelvef = shelve.open(‘shelve_test‘) #開啟一個檔案f[‘book‘] = [1,2,3,4,5] #增加內容f.close()f2 = shelve.open(‘shelve_test‘)print(list(f2.keys()))  # [‘names‘, ‘info_dic‘, ‘book‘]print(f2[‘book‘])

我們來修改一下內容:(只能通過 f[‘book‘] = [1,2,‘肖申克的救贖‘,4,5]) 這樣的方式重新賦值來更改

f[‘book‘][0] = ‘new book‘ 這樣的方式是不可以的。

import shelvef = shelve.open(‘shelve_test‘)  # 開啟一個檔案f[‘book‘] = [1,2,‘肖申克的救贖‘,4,5]f.close()f2 = shelve.open(‘shelve_test‘)print(f2[‘book‘])  # [1, 2, ‘肖申克的救贖‘, 4, 5]

刪除內容:

import shelvef = shelve.open(‘shelve_test‘) #開啟一個檔案del f[‘book‘]f.close()f2 = shelve.open(‘shelve_test‘)print(list(f2.items())) # 列印 : [(‘names‘, [‘python‘, ‘html‘, ‘java‘]), (‘info_dic‘, {‘name‘: ‘jack‘, ‘age‘: 25})]

python序列化_json,pickle,shelve模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.