python - 使用 xml.etree 在 Python 中编写包含欧元符号 (€) 的 xml 文件

标签 python xml xml.etree euro

我正在尝试使用 xml.etree 来读取和写入包含 € 符号的 xml 文件。

我的简化代码如下所示:

optionsdirectory = os.getcwd()
optionsfile = os.path.join(optionsdirectory, "conf")
optionstree = ET.parse(optionsfile)
options = optionstree.getroot()
for option in options:
    if option.tag == "currency":
        option.text = "€"
optionstree.write(optionsfile, encoding="UTF-8")

运行时出现以下错误:

File "C:\curr.py", line 8
    optionstree.write(optionsfile, encoding="UTF-8")
File "C:\Python27\lib\xml\etree\ElementTree.py", line 815, in write
    serialize(write, self._root, encoding, qnames, namespaces)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 934, in _serialize_xml
    _serialize_xml(write, e, encoding, qnames, None)
File "C:\Python27\lib\xml\etree\ElementTree.py", line 932, in _serialize_xml
    write(_escape_cdata(text, encoding))
File "C:\Python27\lib\xml\etree\ElementTree.py", line 1068, in _escape_cdata
    return text.encode(encoding, "xmlcharrefreplace")
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 2114: ordinal not in range(128)

有没有办法使用 xml.etree 将 € 符号写入 xml 文件?

最佳答案

您需要使用 unicode 文字。使用 unicode 转义而不是字符会更容易:

option.text = u"\u20AC"  # Euro sign

当您不使用 unicode 文字而是使用字节(字符串)文字时会发生什么,Python 会尝试使用默认编码(ASCII)将值解码为 un​​icode 文字。这会导致您看到的 UnicodeDecodeError。

如果您真的确实想要使用非转义字符,请确保在顶部指定源文件的编码:

# -*- coding: utf-8 -*-

并确保您的编辑器使用 UTF-8 来保存文件。不过,您仍然必须使用 unicode 文字:

option.text = u"€"

关于python - 使用 xml.etree 在 Python 中编写包含欧元符号 (€) 的 xml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655836/

相关文章:

python - 生成具有正确缩进的 XML 文件

c# - 写入 NameValueCollection

asp.net - XML 包中的 Google 跟踪代码管理器脚本解析错误

python - 如何在 Python 中处理多个相同的未阻塞信号?

python - 使用 PySimpleGui,如何让按钮起作用?

xml - xslt删除具有某些子节点属性的父级

python - 如何使用 xml.etree.ElementTree 访问标签之间的文本

python - etree 克隆节点

python - 安装程序;模块未找到错误 : No module named 'sklearn.utils._cython_blas'

python - 向 numpy 矩阵添加维度