【问题标题】:Character encoding compatibility between python2 and python3python2和python3之间的字符编码兼容性
【发布时间】: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


    【解决方案1】:

    我找到了解决方案。我以二进制模式打开文件,然后在写入之前使用 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)
    

    【讨论】:

      猜你喜欢
      • 2020-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 2019-02-10
      • 1970-01-01
      • 2011-05-13
      相关资源
      最近更新 更多