li=['anny',11,22,'ok','doubi']
#序列化
xu=pickle.dumps(li)
print(xu)
#反序列化
print(pickle.loads(xu))
#将数据序列化后存储到文件中
f= open('test.txt','wb') #pickle只能以二进制格式存
f.write(pickle.dumps(li)) #dumps序列化源数据后写入文件
f.close()
#反序列化读取源数据
f= open('test.txt','rb')
da= pickle.loads(f.read()) #使用loads反序列化
print(da)
import json
"""
json.dump(obj,fp,*,skipkeys = False,ensure_ascii = True,check_circular = True,indent = None,separators = None,default = None,sort_keys = False,** kw)
将obj对象格式化并存储到文件对象中,文件必须为可写的文件句柄,json只产生str对象,不支持bytes对象,所以fp.write()必须支持str输入
skipkeys如果为True,对象的基本类型必须是str,int,float,bool,None
ensure_ascii=True,如果为true则所以传入的非ASCII字符都被转义,如果为false则字符将原样输出
check_circular=True,如果为true容器类型的循环引用检查将被跳过
indent=None,表示数组元素和对象将按指定的值缩进,可以是整数或字符串如'\t'
sort_keys=False,如果为True字典的输出将按键排序
"""
data=[{'k1':'v1','k2':'v2'},{'k3':'v3','k4':'k4'},{'k6':'v6','k5':'k5'}]
with open('test1.txt','w') as pf:
json.dump(data,pf,indent=2,sort_keys=True)
pf.close()
"""
json.dumps(obj,*,skipkeys = False,ensure_ascii = True,check_circular = True,indent = None,separators = None,default = None,sort_keys = False,** kw)
将obj对象格式化为str对象,参数含义和dump相同
"""
data=[{'k1':'v1','k2':'v2'},{'k3':'v3','k4':'k4'},{'k6':'v6','k5':'k5'}]
pi= json.dumps(data,indent=2,sort_keys=True)
print(type(pi))
print(pi)
p2=json.loads(pi)
print(type(p2))
print(p2)