使用Python读取.plist文件数据并记录到内存中

1 投票
2 回答
956 浏览
提问于 2025-04-17 02:10

我有一个压缩文件(zip文件)。在这个压缩文件里,有一个plist文件,叫做“Restore.plist”。我想知道怎么让Python读取这个.plist文件,并在到达某个部分时停止:

<key>SupportedProductTypes</key>
<array>
    <string>iPhone3,1</string>
</array>

我想让Python在“SupportedProductTypes”这个键那里停止,并把它对应的字符串“iPhone3,1”记住,存成一个变量,比如叫“x”,然后打印出这个“x”。我该怎么做呢?

2 个回答

1

试试用xml:

import xml.etree.ElementTree as ET

tree = ET.parse("keys.xml")
doc = tree.getroot()
sup = doc.getiterator("SupportedProductTypes")

print doc.getiterator("string")[0].text

结果是:

iPhone3,1

用这个测试文件,叫做“keys.xml”:

<keys>
<key>SupportedProductTypes</key>
<array>
    <string>iPhone3,1</string>
</array>
</keys>
3

plistlib 是 Python 标准库中的一个模块,用来处理 .plist 文件。你可以参考 这篇 PyMOTW 文章,里面有个简单的教程。

另外,Python 标准库中还有 zipfile 模块里的 ZipFile 类,可以用来读取 ZIP 文件。

撰写回答