标签:建议 python3.x color pickle eva ext c语言 imp read
序列化实现方法:
#不实用模块 # 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‘))
标签:建议 python3.x color pickle eva ext c语言 imp read
原文地址:http://www.cnblogs.com/xiaobai005/p/8013019.html