【发布时间】:2018-03-28 10:59:27
【问题描述】:
我正在使用 ElementTree 编写 plist 文件,我需要在树开始之前添加两行文本,以匹配 Apple 的 plist 语法。以下代码在 python 2.7 中有效,但在 python 3.6 中失败,TypeError: write() argument must be str, not bytes。
import xml.etree.ElementTree as ET
tree = ET.parse('com.input.plist')
with open('com.new.plist', 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n')
tree.write(f, encoding='utf-8')
为了让它在 python3 上运行,我可以这样改变它:
tree = ET.parse('com.input.plist')
with open('com.new.plist', 'w') as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n')
tree.write(f, encoding='unicode')
但这在带有LookupError: unknown encoding: unicode 的python2 中失败了。我怎样才能使它与两个版本兼容?
【问题讨论】:
标签: python xml character-encoding plist elementtree