Python学习之路:son and pickle序列化
Posted Py小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习之路:son and pickle序列化相关的知识,希望对你有一定的参考价值。
序列化实现方法:
#不实用模块 # info ={ # ‘name‘:‘alex‘, # ‘age‘:22 # # } # f = open("test.text","w") # f.write(str(info)) # # f.close() #json 序列化简单数据类型 # import json # # info ={ # ‘name‘:‘alex‘, # ‘age‘:22 # # } # f = open("test.text","w") # f.write(json.dumps(info)) # f.close() #python会跟JAVA,C语言做交互,其中需要一个中间交互语言---json,能处理的都是简单的数据类型 # import json # def sayhi(name): # print("hello,",name) # # info ={ # ‘name‘:‘alex‘, # ‘age‘:22, # ‘func‘:sayhi # # } # f = open("test.text","w") # f.write(json.dumps(info))#报错,函数不可序列化 import pickle#pickle可以序列化Python中所有数据类型 def sayhi(name): print("hello,",name) info ={ ‘name‘:‘alex‘, ‘age‘:22, ‘func‘:sayhi } f = open("test.text","wb") f.write(pickle.dumps(info))
反序列化相应方法:
# f = open("test.text","r") # data = eval(f.read()) # f.close() # # print(data[‘age‘]) # import json # # f = open("test.text","r") # data = json.loads(f.read()) # # print(data[‘age‘]) #pickle只能在Python语言内部使用 import pickle#f反序列化的整个数据对象 def sayhi(name): print("hello,",name) print("hello2,",name) f =open("test.text","rb") data =pickle.loads(f.read())#data=pickle.load(f) print(data["func"](‘alex‘))
Python3.X可以多次json.dumps,但是只能一次json.loads,建议每个程序只一次json.dumps,一次json.loads
import json info ={ ‘name‘:‘alex‘, ‘age‘:22 } f = open("test.text","w") f.write(json.dumps(info)) info[‘age‘]=21 f.write(json.dumps(info)) f.close()
pickle.dumps与pickle.dump;pickle.loads与pickle.load
import pickle#pickle可以序列化Python中所有数据类型 def sayhi(name): print("hello,",name) info ={ ‘name‘:‘alex‘, ‘age‘:22, ‘func‘:sayhi } f = open("test.text","wb") pickle.dump(info,f)#f.write(pickle.dumps(info)) f.close() ---------------------------------------------------------------- #pickle只能在Python语言内部使用 import pickle#f反序列化的整个数据对象 def sayhi(name): print("hello,",name) print("hello2,",name) f =open("test.text","rb") data =pickle.loads(f.read())#data=pickle.load(f) print(data["func"](‘alex‘))
以上是关于Python学习之路:son and pickle序列化的主要内容,如果未能解决你的问题,请参考以下文章
python之路---23 模块 os sys pickle json