python2和python3之间的字符编码兼容性

时间:2018-03-28 10:59:28

标签: python xml character-encoding plist elementtree

我正在使用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中失败了。如何使这两个版本兼容?

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我以二进制模式打开文件,然后在写入之前使用string.encode()。

with open('com.new.plist', 'wb') as f:
    xml_header = '<?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'
    f.write(xml_header.encode())
    tree.write(f)