python學習之路-----序列化,python-----序列化

來源:互聯網
上載者:User

python學習之路-----序列化,python-----序列化

我們把變數從記憶體中變成可儲存或傳輸的過程稱之為序列化,在Python中叫pickling,在其他語言中也被稱之為serialization,marshalling,flattening等等,都是一個意思。

序列化之後,就可以把序列化後的內容寫入磁碟,或者通過網路傳輸到別的機器上。

反過來,把變數內容從序列化的對象重新讀到記憶體裡稱之為還原序列化,即unpickling。

Python提供了pickle模組來實現序列化。

pickle模組中
pickle.dumps()方法將任意對象序列化成一個bytes,然後就可以將這個bytes寫入檔案,或者用pickle.dumps()直接將對象序列化後寫入一個file-like object
例如:
import pickle
d=dict(name='bob',age=20,score=80)
pickle.dumps(d)
--->序列化對象d
b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x14X\x05\x00\x00\x00scoreq\x02KXX\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00Bobq\x04u.'


或者使用pickle.dump():
f=open('dump.txt','wb')
pickle.dump(d,f)
f.close()
直接將d寫入f中

即 pickle.dump(object,file-like)或pickle.dumps(object) 將對象序列化後寫入檔案(file-like)[記憶體--->外存]

pickle.load(file-like)將檔案中的內容讀取到記憶體 還原序列化

***json 模組
*-*將記憶體中的對象序列化後寫入檔案中
json.dumps(obj,defaullt=iterator) --->obj是要存入檔案的對象,iterator是將該對象轉化為dict的函數
比如:
class student(object):
def __init__(self,name,score,age):
self.__name=name
self.__score=score
self.__age=age

@property
def Name(self):
return self.__name
@property
def Score(self):
return self.__score
@property
def Age(self):
return self.__age

def student2dict(std):
return {
'name':std.Name,
'score':std.Score,
'age':std.Age,
}

s=student('huanglei',100,20)

#jd=json.dumps(s,default=student2dict)#jd為json序列化後的對象可以存入(json)檔案中
jd=json.dumps(s,default=lambda obj:obj.__dict__)#jd為json序列化後的python對象可以存入(json)檔案中
print(jd)
#將序列化後的對象寫入(json)檔案
with open('file_js.json','w') as f:
f.write(jd)

*-*讀取json的內容到記憶體中

#還原序列化
#如果我們要把JSON還原序列化為一個Student對象執行個體,
# loads()方法首先轉換出一個dict對象,
# 然後,我們傳入的object_hook函數負責把dict轉換為Student執行個體:
def dict2student(dts):
return student(dts['name'],dts['score'],dts['age'])

f1= open('file_js.json','rb')
s=f1.read()
f1.close()

#json.loads(s,object_hook=none)函數 參數s必須是基本類型:
# Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray``
#instance containing a JSON document) to a Python object
#不能是filestream (最開始想投機取巧將f1傳入s 報錯了^_^)
x=json.loads(s,object_hook=dict2student)
print('從json檔案中讀取到的內容為:%s,%d,%d',x.Name,x.Score,x.Age)

以上都是在廖老師的網站(https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000)上學習的,可能並不是那麼深入,但是都是通過自己實踐得出來的結果,還請大家多多指教

這是我第一次寫部落格,感覺有點吃力,但是我相信堅持下來一定會有收穫的!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.