python - 在Python中解析plist文件

标签 python plist

我的 Python 代码有问题。我有一个 plist 文件。

Info.plist

<plist>
  <dict>
    <key>Apple Car Version</key>
    <string>1.0</string>
    <key>Last Backup Date</key>
    <date/>
    <key>Product Type</key>
    <string>iPad2,5</string>
    <key>Product Version</key>
    <string>9.3.1</string>
  </dict>
</plist>

我的Python代码:

import os
import plistlib

def main():

   fileName=os.path.expanduser('Info.plist')

   if os.path.exists(fileName):

      pl=plistlib.readPlist(fileName)

      if 'Product Version' in pl:
         print( 'The aString value is %s\n' % pl['Apple Car Version'])

      else:
         print( 'There is no Apple Car Version in the plist\n')

   else:
      print( '%s does not exist, so can\'t be read' % fileName)

if __name__ == '__main__':
   main()

好吧,我写了一些代码,但是我现在面临更大的问题,我发现这不是我的代码,而是我的 plist The Last Backup Date in the plist 导致错误。有没有一种方法可以让我只能解析字符串,而不能像<date/>那样

顺便说一句,如果您想知道,这个 plist 是由 iTunes 制作的

最佳答案

那个 plist 文件根本不是格式良好的 xml,所以我怀疑它是否能工作。我认为你(至少)需要一个根 plist 元素和一个 dict 包装器:

<plist>
  <dict>
    <key>Apple Car Version</key>
    <string>1.0</string>
  </dict>
</plist>

然后 pl 的键将是您在文件中实际定义的键,因此在本例中为“Apple Car Version”:

print(pl['Apple Car Version'])

关于python - 在Python中解析plist文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37955056/

相关文章:

python - 在 jupyter 笔记本上的同一行上打印

python - 抓取雅虎盈利日历

objective-c - 实现 NSOutlineView 来编辑 plist 文件的内容

macos - 如何以编程方式确定用户是否已将其 Mac 设置为 "set date and time automatically"?

python - 具有非数字类型的 groupby/aggregate 数据框

python 不会长大

python - 使用正则表达式修改字符串

iphone - 客观计数器

ios - 在 swift 2.1 中写入/读取 Plist

iphone - 如何在 xcode 的文件模板中创建文件夹?