標籤:建議 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 jsoninfo ={ ‘name‘:‘alex‘, ‘age‘:22}f = open("test.text","w")f.write(json.dumps(info))info[‘age‘]=21f.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序列化