Skip to main content
 首页 » 编程设计

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

2025年05月04日18zhoujg

我正在尝试使用 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"€"