Serialization of
Serialization refers to converting the data type in memory into a string so that it can be stored on the hard disk or transmitted over the network to the remote, because the hard disk or the network can only accept bytes
- Turns memory data into characters, called serialization
- Turn characters into memory data, called deserialization
Module Jsonjson.dumps () serializes an object
import jsondata = { ‘roles‘:[ {‘role‘:‘monster‘,‘type‘:‘pig‘,‘life‘:50}, {‘role‘:‘hero‘,‘type‘:‘关羽‘,‘life‘:80}, ]}d = json.dumps(data) #转成字符串print(type(d))print(d)
Printing results:
<class ‘str‘>{"roles": [{"role": "monster", "type": "pig", "life": 50}, {"role": "hero", "type": "\u5173\u7fbd", "life": 80}]}
Json.lodads () Loading data from an object
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 () Serializes an object into a file
import jsondata = { ‘roles‘:[ {‘role‘:‘monster‘,‘type‘:‘pig‘,‘life‘:50}, {‘role‘:‘hero‘,‘type‘:‘关羽‘,‘life‘:80}, ]}f = open(‘test.json‘,mode=‘w‘)json.dump(data, f) #转成字符并写入文件
Result: Data is written to the file
Json.load () loads data from an open file handle
import jsonf = open(‘test.json‘,‘r‘)data = json.load(f)print(data[‘roles‘])
Print:
[{‘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)
Results:
Description: can dump multiple data and write to file
Let's do it now. json.load
f = open(‘json_file.json‘,‘r‘,encoding=‘utf-8‘)json.load(f)# 程序报错:json.decoder.JSONDecodeError
Load only once, and JSON format has a problem, will error
------------------------------------------------Split Line------------------------------------------------
Module Pickle
import pickledata1 = {‘name‘:‘nurato‘,‘skill‘:‘螺旋丸‘}f = open(‘data.pkl‘,‘wb‘)pickle.dump(data1,f)
Result: A file named Data.pkl was created
import picklef = open(‘data.pkl‘,‘rb‘)d = pickle.load(f)print(type(d))print(d)#<class ‘dict‘>#{‘name‘: ‘nurato‘, ‘skill‘: ‘螺旋丸‘}
About JSON and Pickle
Json:
Advantages: Cross-language, small size
Cons: Only support int\str\list\tuple\dict
Pickle:
Pros: Designed for Python and supports all Python data types
Cons: can only be used in Python, the storage data occupy large space
---------------------------------------Split Line-------------------------------------------
Serialization of shelve modules
import shelvef = shelve.open(‘shelve_test‘) #打开一个文件names = [‘python‘, ‘html‘, ‘java‘]info = {‘name‘: ‘jack‘, ‘age‘: 25}f[‘names‘] = namesf[‘info_dic‘] = infof.close()
Result: The Shelve_test file is created
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}
Add Content:
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‘])
Let's modify the content: (Only through f[‘book‘] = [1,2,‘肖申克的救赎‘,4,5]
) re-assigning values in such a way as to change
f[‘book‘][0] = ‘new book‘
Such a way is not possible.
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]
Delete content:
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 Serialization _json,pickle,shelve Module