Python 資料永續性 - plistlib 模組



plist 格式主要由 MAC OS X 採用。這些檔案基本上是 XML 文件。它們儲存和檢索物件屬性。Python 庫包含一個 plist 模組,用於讀取和寫入“屬性列表”檔案(它們通常以“.plist”為副檔名)。

從某種意義上說,plistlib 模組與其他序列化庫非常相似,它也提供了 dumps() 和 loads() 函式來獲得 Python 物件的字串表示,以及 load() 和 dump() 函式來進行磁碟操作。

下列字典物件維護了屬性(鍵)和對應的值:

proplist = {
   "name" : "Ganesh",
   "designation":"manager",
   "dept":"accts",
   "salary" : {"basic":12000, "da":4000, "hra":800}
}

為了將這些屬性寫入磁碟檔案中,我們呼叫 plist 模組中的 dump() 函式。

import plistlib
fileName=open('salary.plist','wb')
plistlib.dump(proplist, fileName)
fileName.close()

相反,要回讀屬性值,請如下使用 load() 函式:

fp= open('salary.plist', 'rb')
pl = plistlib.load(fp)
print(pl)
廣告
© . All rights reserved.