readPlist出现DeprecationWarning错误 & AttributeError异常

5
我正在寻找一种方法来访问plist文件:/Library/Preferences/com.apple.iPod.plist,以访问其中的序列号。
以下是我当前的代码--
import os
import plistlib

fileName=os.path.expanduser('/Users/Ryan/Library/Preferences/com.apple.iPod.plist')

pl=plistlib.readPlist(fileName)

for left, right in pl.items(): 
   for values in right.values():
         print(values['Serial Number'])

我一直在得到结果,但同时也出现了一些快速错误。我得到了这个:
plist.py:8: DeprecationWarning: The readPlist function is deprecated, use load() instead pl=plistlib.readPlist(fileName)

同时还有这个:

  File "plist.py", line 16, in <module>
    for values in right.values():
   AttributeError: 'bool' object has no attribute 'values'

我猜使用load函数应该很简单,但是在网上找到的教程修改它以满足我的需求让我费了好大的劲。

至于那个布尔属性错误(boolean AttributeError),我不知道我做错了什么。

谢谢!

2个回答

7
为了消除废弃错误,请将包含readPlist的行替换为
with open(fileName, 'rb') as f:
    pl = plistlib.load(f)

您的第二个问题似乎是由于plistlib更改引起的:

在版本3.7中更改:结果中的Dict值现在是普通字典。您不能再使用属性访问来访问这些字典的项。

我遇到了类似的问题:AttributeError: 'dict' object has no attribute 'children',通过将someObj.children[:]替换为someObj['children']来解决了该问题。我认为您调用right.values()时也可能类似,但如果没有实际的期望plist示例,很难确定。

-1

当我转换到Python3时,我遇到了同样的问题。我使用了ne plistlb.load,但遇到了以下异常错误,我还没有找到解决方案。

在Python2中工作:

#info = plistlib.readPlist(test_path)

Python3:

with open(test_path, 'rb') as fp:
    pl = plistlib.load(fp)
print(test_path)

错误:

Traceback (most recent call last):
  File "/path_to_python.py", line 70, in <module>
    pl = plistlib.load(fp)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/plistlib.py", line 869, in load
    raise InvalidFileException()

plistlib.InvalidFileException: 无效的文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接