ElementTree TypeError "write() argument must be str, not bytes" in Python3

Specify encoding of string while writing the xml file.

Like decode(UTF-8) with write(). Example: file.write(etree.tostring(doc).decode(UTF-8))


As it turns out, tostring, despite its name, really does return an object whose type is bytes.

Stranger things have happened. Anyway, here's the proof:

>>> from xml.etree.ElementTree import ElementTree, tostring
>>> import xml.etree.ElementTree as ET
>>> element = ET.fromstring("<a></a>")
>>> type(tostring(element))
<class 'bytes'>

Silly, isn't it?

Fortunately you can do this:

>>> type(tostring(element, encoding="unicode"))
<class 'str'>

Yes, we all thought the ridiculousness of bytes and that ancient, forty-plus-year-old-and-obsolete encoding called ascii was dead.

And don't get me started on the fact that they call "unicode" an encoding!!!!!!!!!!!


The output file should be in binary mode.

f = open('sample.svg', 'wb')

Try:

f.write(et.tostring(doc).decode(encoding))

Example:

f.write(et.tostring(doc).decode("utf-8"))