目录
- 初识序列化与反序列化
- 可序列化的数据类型
- Python中的json
- Python中的pickle
初识序列化
可序列化的数据类型
- number、str、list、tuple、dict
- 类、函数、集合无法进行序列化
Python的json模块
Python的pickle模块
实战
import json
def read(path):
with open(path, 'r') as f:
data = f.read()
return json.loads(data)
def write(path, data):
with open(path, 'w', encoding='utf-8') as f:
if isinstance(data, dict):
_data = json.dumps(data)
f.write(_data)
else:
raise TypeError('data is dict')
return True
data = {'name':'insane', 'age':18, 'top':178}
if __name__ == '__main__':
write('test.json', data)
result = read('test.json')
print(result, type(result))
result['sex'] = 'boy'
write('test.json', result)
print(result)
{"name": "insane", "age": 18, "top": 178, "sex": "boy"}
{'name': 'insane', 'age': 18, 'top': 178} <class 'dict'>
{'name': 'insane', 'age': 18, 'top': 178, 'sex': 'boy'}
Process finished with exit code 0