我正在尝试使用 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 文件?