Mi-krater
Mi-krater

Reputation: 619

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

I have a program that is creating an XML file and writing it to the system. My issues occurs when I encounter characters like '\u1d52', the system throws the error. "charmap' codec can't encode character."

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

Most of the solutions online seem to suggest that simply adding some encoding will fix the issue, however when I try to add encoding I instead get the following error message: "write() argument must be str, not bytes"

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

I'm experienced in javascript and C#, but fairly new to python. Is there something simple I am missing?

Upvotes: 0

Views: 615

Answers (1)

CodeMonkey
CodeMonkey

Reputation: 23748

\u1d52 is a latin small letter 'o' character probably cut-paste from Windows and iso-8859-1 encoding should work.

Try:

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

The ElementTree.write() function uses the following parameters:

*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

Upvotes: 1

Related Questions