python 基础语法 - 序列化
Json & pickle模块
1.Json 和 pickle的区别:
Json:跨平台性强,可以在多平台上使用
Pickle:只能在python中使用
Json:只能存字符串格式的json,pickle都可以存
2.json序列化:
例子:写入:保存文件的内容为json格式的字符串内容
import json dic={'name':'dongye','age':24 } with open('a.json','w') as f: f.write(json.dumps(dic))
例子:在文件中读取json格式的字符串到内存中,并转换成字典
with open('a.json','r') as f: data=f.read() dic=json.loads(data) print(dic['name'])
优化写法:
写入:
dic={'name':'dongye','age':'18'} with open('d.pkl','wb') as f: f.write(pickle.dumps(dic))
读取:
a=json.load(open('b.json','r'))['name'] print(a)
3.pickel 序列化:
例子:写入:
注意:pickle方式写入文件,文件内容是bytes类型不可以读取
dic={'name':'dongye','age':'18'} with open('d.pkl','wb') as f: f.write(pickle.dumps(dic))
执行结果:
例子:读取
dic=pickle.loads(f.read()) print(dic)
执行结果:
![](https://images2018.cnblogs.com/blog/1213077/201808/1213077-20180814194448663-1818815264.png)
优化写法:
例子:写入:
dic={'name':'dongye','age':'18'} pickle.dump(dic,open('e.pkl','wb'))
例子:读取
dic=pickle.load(open('e.pkl','rb'))['name'] print(dic)