python-序列化
标签:json pickle
序列化的基本概念介绍:
01什么是序列化序列化:把内存中的数据转成一种中间格式(json / pickle), 然后存放到硬盘中,永久保存反序列化:从文件中读出(json / pickle)格式,然后返解成python的数据类型
02为什么要序列化1、数据结构持久化
2、跨平台数据交互
03如何进行序列化,反序列化json:缺点:只能支持部分python的数据类型优点:所有的语言都支持json格式
应用:如果需要考虑跨平台性,则需要用json格式pickle缺点:只有python支持pickle格式优点:pickle能够支持所有的python数据类型
应用:如果不需要考虑跨平台性,则可以用pickle格式
Import json
import jsondic={‘name‘:‘egon‘,‘age‘:18}print(json.dumps(dic))#{"name": "egon", "age": 18} #python的idc类型就是对应json的{}
dic={‘name‘:‘egon‘,‘age‘:18,‘is_beautiful‘:True}print(json.dumps(dic))#{"name": "egon", "age": 18, "is_beautiful": true} Python的True对应json的true
dic={‘name‘:‘egon‘,‘age‘:18,‘is_beautiful‘:True}res=json.dumps(dic)print(res,type(res)){"name": "egon", "age": 18, "is_beautiful": true} <class ‘str‘> json的tsring对应python的str
序列化: 把字典序列化到文件中的简单的写法:res=json.dumps(dic) # 强调,json格式不识别单引号
print(res,type(res))
with open(‘user.json‘,‘w‘,encoding=‘utf-8‘) as f: #存入到文件user.json可以不加,提醒是json格式的文件,字符串是wt,可以省略t,f.write(res)
反序列化: 现在数据存入到了user.json文件,注释代码文件中的内容,此时内存中没有这个文件,此时要取这个内容要从user.json文件中去拿with open(‘user.json‘,‘r‘,encoding=‘utf-8‘) as f:res=f.read()dic=json.loads(res)print(dic[‘name‘])
强调,json格式不识别单引号with open(‘user1.json‘,‘r‘,encoding=‘utf-8‘) as f:res=f.read()dic=json.loads(res)print(dic[‘x‘])user1.json{‘x‘:1,‘y‘:true} #反序列化的时候会报错,# obj,end = self.scan_once(s, idx)#json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1){"x":1,"y":true} #反序列化的时候会报错,非要用双引号,不支持单引号,改成双引号能取出#egon
简写的格式:序列化:dic={‘name‘:‘egon‘,‘age‘:18,‘is_beautiful‘:True}
with open(‘user2.json‘,‘w‘,encoding=‘utf-8‘) as f:json.dump(dic,f) #第一个参数是序列化的对象,第二个参数是要打开的文件,sjon.dum可以直接把字典放入到文件,就不用再掉f.read
反序列化:with open(‘user.json‘, ‘r‘, encoding=‘utf-8‘) as f:dic = json.load(f)print(dic[‘name‘])
import pickle
序列化:pickle可以序列化任意python的数据类型print(json.dumps({1,2,3}))print(pickle.dumps({1,2,3}))
dic={‘name‘:‘egon‘,‘age‘:18,‘is_beautiful‘:True}
res=pickle.dumps(dic)with open(‘user3.pkl‘,‘wb‘) as f:f.write(res)
反序列化:with open(‘user3.pkl‘,‘rb‘) as f:res=f.read()
dic=pickle.loads(res)print(dic[‘name‘])
简单写法
序列化:
dic={‘name‘:‘egon‘,‘age‘:18,‘is_beautiful‘:True}with open(‘user4.pkl‘,‘wb‘) as f:pickle.dump(dic,f)
反序列化
with open(‘user4.pkl‘, ‘rb‘) as f:dic = pickle.load(f)print(dic[‘name‘])
总结:Day-6-8
序列化:python – –>json反序列化:json – –>python
序列化:pythondic到jsondumps – —>json – —->file【open –>write】dump
反序列化:loads – —->readload
json支持多平台,使用与跨平台项目的开发pickle只支持python
json格式的字符串,既然是字符串他有两个用处1、绑定函数,对数据进行持久化2、给别的平台发
python-序列化
标签:json pickle
原文地址:http://blog.51cto.com/firephoenix/2117654