Python Data Persistence 简明教程

Python Data Persistence - Plistlib Module

plist 格式主要用于 MAC OS X。这些文件基本上是 XML 文档。它们存储和检索对象的属性。Python 库包含 plist 模块,用于读取和写入“属性列表”文件(它们通常具有 .plist”扩展名)。

The plist format is mainly used by MAC OS X. These files are basically XML documents. They store and retrieve properties of an object. Python library contains plist module, that is used to read and write 'property list' files (they usually have .plist' extension).

plistlib 模块在意义上与其他序列化库比较类似,它也提供 dumps() 和 loads() 函数用于 Python 对象的字符串表示,以及 load() 和 dump() 函数用于磁盘操作。

The plistlib module is more or less similar to other serialization libraries in the sense, it also provides dumps() and loads() functions for string representation of Python objects and load() and dump() functions for disk operation.

以下字典对象维护着属性(键)和相应的价值 −

Following dictionary object maintains property (key) and corresponding value −

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

为了将这些属性写到磁盘文件中,我们调用 plist 模块中的 dump() 函数。

In order to write these properties in a disk file, we call dump() function in plist module.

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

相反,为了读回属性值,按如下所示使用 load() 函数 −

Conversely, to read back the property values, use load() function as follows −

fp= open('salary.plist', 'rb')
pl = plistlib.load(fp)
print(pl)