json和pickle数据序列化和反序列化
json序列化
info = {
'name':'alex',
'age':22
}
f =open("test.txt",'w')
f.write(str(info))#把一个字典转换成字符串 从内存存到硬盘的过程叫序列化
f.close()
importjson
info = {
'name':'alex',
'age':22
}
f =open("test.txt",'w')
#print(json.dumps(info))
f.write(json.dumps(info))#把一个字典转换成字符串 从内存存到硬盘的过程叫序列化
f.close() #序列化dumps 函数不可以序列化 只能处理简单的跨平台数据交互
importjson
info = {
'name':'alex',
'age':22
}
f =open("test.txt","w")
json.dump(info,f)
info["age"]=21
json.dump(info,f)#一般只dump一次,因为3.x版本只能load一次,dump多次没意义
f.close()
json反序列化
f =open("test.txt",'r')
data =eval(f.read())
f.close()
print(data['age'])
importjson
f =open("test.txt",'r')
data = json.loads(f.read())#反序列化loads
print(data['age'])
importjson
f =open("test.txt",'r')
#data = json.load(f) #等于data= json.loads(f.read()) 会报错 3.X只能load一次
forlineinf:
print(line)
pickle序列化
importpickle
defsayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f =open("test.txt",'wb')
#print(pickle.dumps(info))
f.write(pickle.dumps(info))#pickle可以序列化所有的数据
f.close()
importpickle
defsayhi(name):
print("hello,",name)
info = {
'name':'alex',
'age':22,
'func':sayhi
}
f =open("test.txt","wb")
pickle.dump(info,f)# 等于f.write(pickle.dumps(info))
#pickle.dump(对象,文件)
f.close()
pickle反序列化
importpickle
defsayhi(name):
print("hello2,",name)
f =open("test.txt",'rb')
data = pickle.loads(f.read())#反序列化loads pickle只能用在python里面,java不认
print(data["func"]("alex"))#反序列化只要函数名一样就可以,序列化的是整个的数据对象
importpickle
defsayhi(name):
print("hello2,",name)
f=open("test.txt",'rb')
data = pickle.load(f)#等于data= pickle.loads(f.read())
print(data["func"]("alex"))
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。