使用python读取非XML格式的plist文件

时间:2018-04-03 10:49:35

标签: python plist

我正在阅读处于plist(属性列表)格式的MacOS数据,该格式不是XML格式,不是二进制格式,而是另一种ascii格式。例如:

addr= {
    City = "San Francisco Bay Area";
}

我正在尝试将其解析为Python字典。不幸的是,当我尝试解析它时,plistlib.loads会返回InvalidFileException()

import plistlib

plist=b"""
addr= {
    City = "San Francisco Bay Area";
}
"""

print( plistlib.loads( plist ) )

产地:

Traceback (most recent call last):
  File "x.py", line 9, in <module>
    print( plistlib.loads( plist ) )
  File "/Users/simsong/anaconda/lib/python3.6/plistlib.py", line 1024, in loads
    fp, fmt=fmt, use_builtin_types=use_builtin_types, dict_type=dict_type)
  File "/Users/simsong/anaconda/lib/python3.6/plistlib.py", line 1009, in load
    raise InvalidFileException()
plistlib.InvalidFileException: Invalid file

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您正在谈论JSON格式的plist文件。你的例子不是JSON。

让我们从这个sample plist in XML

开始
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist SYSTEM "file://localhost/System/Library/DTDs/PropertyList.dtd">
<plist version="1.0">
<dict>
    <key>Author</key>
    <string>William Shakespeare</string>
    <key>Lines</key>
    <array>
        <string>It is a tale told by an idiot,</string>
        <string>Full of sound and fury, signifying nothing.</string>
    </array>
    <key>Birthdate</key>
    <integer>1564</integer>
</dict>
</plist>

并将其转换为JSON格式:

plutil -convert json sample.plist 

{"Author":"William Shakespeare","Birthdate":1564,"Lines":["It is a tale told by an idiot,","Full of sound and fury, signifying nothing."]}

现在您可以使用JSON库阅读此内容。

import json

plist_text = '{"Author":"William Shakespeare","Birthdate":1564,"Lines":["It is a tale told by an idiot,","Full of sound and fury, signifying nothing."]}'

plist = json.loads(plist_text)

print('The author is ' + plist['Author'])

输出:

$ python3 plist.py 
$ The author is William Shakespeare