"""
1、什么是序列化与反序列化
内存中某一类的数据---------------》特殊的格式
内存中某一类的数据《---------------特殊的格式
2、为何要序列化
1、存档:把内存中的数据持久化到硬盘
2、跨平台交互数据
在python中:
存档=》推荐用pickle格式
跨平台交互=》推荐用json格式
3、如何序列化
"""
# 一:low的序列化与反序列化方式
# 1.序列化
items = ["圣剑", "蝴蝶", "BKB"]
dic_str = str(items)
with open('db.txt', mode='wt', encoding="utf-8") as f:
f.write(dic_str)
# 2.反序列化
with open('db.txt', mode='rt', encoding='utf-8') as f:
data = f.read() # "['圣剑', '蝴蝶', 'BKB']"
items = eval(data)
print(items[0])
# 二:json
# 优点:跨平台交互数据
# 缺点:无法识别所有的python数据类型
# 注意:json格式的字符串里不能包含单引号
import json
# 序列化方式一:
t = {"a": 1, "b": 2} # 字典=======》json格式的字符串:"[1,2,3]"
res = json.dumps(t)
print(res, type(res))
with open("a.json", mode='wt', encoding='utf-8') as f:
f.write(res)
# json反序列化方式一:
with open("a.json", mode='rt', encoding='utf-8') as f:
data = f.read()
dic = json.loads(data)
print(dic, type(dic))
res = json.loads('{"k1":111}')
print(res['k1'])
# json序列化方式二:
t = {"a": 1, "b": 2} # 字典=======》json格式的字符串:"[1,2,3]"
with open("b.json", mode='wt', encoding='utf-8') as f:
json.dump(t, f)
# json反序列化方式二:
with open("b.json", mode='rt', encoding='utf-8') as f:
dic = json.load(f)
print(dic, type(dic))
# 三:pickle
# 优点:可以识别所有python类型
# 缺点:只能用于python中,无法跨平台交互
import pickle
s = {1, 2, 3, 4, 5}
res = pickle.dumps(s)
# print(res,type(res))
with open('a.pkl', mode='wb') as f:
f.write(res)
with open('a.pkl', mode='rb') as f:
data = f.read()
s = pickle.loads(data)
print(type(s))
41 json和pickle模块
最新推荐文章于 2021-09-20 19:59:00 发布