Python學習之路:son and pickle序列化

來源:互聯網
上載者:User

標籤:建議   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序列化

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.