序列化:
1.json
2.pickle
4个方法 2组
dumps loads -- 用于网络传输
dump load -- 用于文件存储
dic = {"key": 1}
lst = [1,2,3,4]
手写
new_dic = {}
k,v = dic.replace("{","").replace("}","").replace('"',"").split(":")
new_dic[k] = v
print(new_dic["key"])
import json # 重点
s = json.dumps(dic)
print(s,type(s))
d = json.loads(s)
print(d,type(d))
s = json.dumps(lst) #序列
l = json.loads(s) # 反序列
print(l,type(l))
import json
def func():
print(11)
print(json.dumps(func))
将数据类型转换成字符串(序列化),将字符串转成原数据类型(反序列)
能够序列: 字典,列表,元组序列后变成列表
dic = {"key":1}
json.dump(dic,open("a","a",encoding="utf-8")) # 将源数据类型转换成字符串,写入到文件中
print(json.load(open("a","r",encoding="utf-8"))['key']) # 将文件中字符串转成源数据类型
dic = {"key":"宝元"}
f = open("a","a",encoding="utf-8")
f.write(json.dumps(dic)+"\n")
f.write(json.dumps(dic)+"\n")
f.write(json.dumps(dic)+"\n")
f.write(json.dumps(dic)+"\n")
f1 = open("a","r",encoding="utf-8")
for i in f1:
print(json.loads(i),type(json.loads(i)))
dic = {"meet":27,"太白":30,"alex":36,"wusir":33}
print(json.dumps(dic,ensure_ascii=False,sort_keys=True))
pickle
只有python有,几乎可以序列python中所有数据类型,匿名函数不能序列
import pickle
def func():
print(1)
a = pickle.dumps(func) # 将原数据类型转换成类似字节的内容
print(pickle.loads(a)) # 将类似字节的内容转换成原数据类型
转载于:https://www.cnblogs.com/python25/p/11402593.html