大橙子网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

json,pickle模块

序列化: dumps
把内存的数据结构保存下来

import json
dic={'a':1}
res1=json.dumps(dic)
re2=str(dic)
print(res1,type(res1))   #json格式都是用的双引号
print(res2,type(res2))   

x=None
res=json.dumps(x)
print(res,type(res))

import json  #把python格式转化为json格式
user={'name':'xiaoxiao','age':18,'ng':True}  
with open('user.json','w',encoding='utf-8') as f:
    f.write(json.dumps(user))

import json    #同上
user={'name':'xiaoxiao','age':18,'ng':True} 
json.dump(user,open('user_new.json','w',enccoding='utf-8'))   #dump合并成一行

反序列化:loads
import json      
with open('user.json','r',encoding='utf-8') as f:
    user=json.loads(f.read())   #以json格式读取文件内容
    print(user.['name'])

import json 
u=json.load(open('user.json','r',encoding='utf-8'))    #同上,load合并成一行
print(u['age'])

json_res={"name":'xi'}    #json只能用双引号
print(json.load(json_res))

pickle:序列化,能支持所有的Python类型,并以byte类型打开
improt pickle,json
s={1,2,3,4}
#print(json.dumps(s))
print(pickle.dumps(s))

with open('s.pkl','wb') as f:
    f.write(pickle.dumps(s))

pickle.dump(s,open('s.pkl','wb')) #同上

#pickle反序列化
import pickle
with open('s.pkl','rb') as f:
    s=pickle.loads(f.read())
    print(s,type(s))

s=pickle.load(open('s.pkl','rb'))  #同上
print(s,type(s))

标题名称:json,pickle模块
网页地址:http://dzwzjz.com/article/pjsogg.html
在线咨询
服务热线
服务热线:028-86922220
TOP