Python,写入 XML 文件 - 'charmap' 编解码器无法编码字符。当包括编码修复时,get 必须是 str,而不是 bytes

Python, writing an XML file - 'charmap' codec can't encode character. When including encoding to fix, get must be str, not bytes

我有一个程序正在创建一个 XML 文件并将其写入系统。 当我遇到像 '\u1d52' 这样的字符时,我的问题就出现了,系统会抛出错误。 “charmap' 编解码器无法编码字符。”

tree = ET.ElementTree(root)
tree.write("Cool_Output.xml", 'w'), encoding='unicode')

大多数在线解决方案似乎都建议只需添加一些编码即可解决问题,但是当我尝试添加编码时,却收到以下错误消息: “write() 参数必须是 str,而不是字节”

tree = ET.ElementTree(root)
tree.write("Cool_Output.xml", 'w', encoding="utf-8"))

我在 javascript 和 C# 方面很有经验,但对 python 还是个新手。 我缺少一些简单的东西吗?

\u1d52 是一个拉丁文小写字母 'o' 字符,可能是从 Windows 剪切粘贴的,并且 iso-8859-1 编码应该可以工作。

尝试:

tree = ET.ElementTree(root)
tree.write("Cool_Output.xml", encoding='iso-8859-1')

ElementTree.write()函数使用了以下参数:

*file_or_filename* -- file name or a file object opened for writing

*encoding* -- the output encoding (default: US-ASCII)

*xml_declaration* -- bool indicating if an XML declaration should be
                     added to the output. If None, an XML declaration
                     is added if encoding IS NOT either of:
                     US-ASCII, UTF-8, or Unicode

*default_namespace* -- sets the default XML namespace (for "xmlns")

*method* -- either "xml" (default), "html, "text", or "c14n"

*short_empty_elements* -- controls the formatting of elements
                          that contain no content. If True (default)
                          they are emitted as a single self-closed
                          tag, otherwise they are emitted as a pair
                          of start/end tags