保存python plistlib数据(修订版)

时间:2011-09-13 15:38:51

标签: python

如何使用此工作代码:

import plistlib, time
import zipfile


from contextlib import closing
import os



with closing(zipfile.ZipFile("fw.zip")) as zfile:
     for info in zfile.infolist():
        if info.filename.endswith('Restore.plist'):
            zfile.extract(info)

import plistlib as pl
p=pl.readPlist("Restore.plist")
print p["ProductType"]
print p["ProductVersion"]
print p["ProductBuildVersion"]
outputfile = open('output.txt', 'w')
outputfile.write( p["ProductVersion"] )
outputfile.write( ' ')
outputfile.write( p["ProductType"] )
outputfile.write( ' ')
outputfile.write( p["ProductBuildVersion"] )
outputfile.close()

并使用它在此plist中的“update”键下写出字符串,看看update key是如何在另一组名为“RestoreRamDisks”的键下?

<key>RestoreRamDisks</key>#this is the key that the "update" key is under
<dict>
    <key>Update</key>#here is the update key I'm talking about
    <string>018-7074-092.dmg</string>#this is what I want python to spit out
    <key>User</key>
    <string>018-7082-092.dmg</string>
</dict>

为了澄清,我只想使用上面相同的方法来获取“更新”键的信息。困扰我的部分是“更新”键位于另一个名为“RestoreRamDisks”的键下面。当要求找到“更新”键时,我希望这个程序吐出018-7074-092.dmg ..

1 个答案:

答案 0 :(得分:1)

print p["RestoreRamDisks"]时会发生什么?你可以通过简单地做

来获得价值
p["RestoreRamDisks"]["Update"]
# If your plist may not contain a key called "RestoreRamDisks"
# use this instead
p.get("RestoreRamDisks", dict(Update=None)).get("Update", None)
# This will get the value if available, otherwise it will
# evaluate to None