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

There was a problem creating the .SVG file with Python3 and ElementTree.

    from xml.etree import ElementTree as et
    doc = et.Element('svg', width='480', height='360', version='1.1', xmlns='http://www.w3.org/2000/svg')

    #Doing things with et and doc

    f = open('sample.svg', 'w')
    f.write('<?xml version=\"1.0\" standalone=\"no\"?>\n')
    f.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n')
    f.write('\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n')
    f.write(et.tostring(doc))
    f.close()

The et.tostring (doc) function throws a TypeError parameter "write () must be str, not bytes". I do not understand this behavior, "et" should convert ElementTree-Element to string? It works in python2, but not in python3. What have I done wrong?

+9
source share
5 answers

As it turned out, tostringdespite its name, it really returns an object whose type bytes.

Strange 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'>

Stupid, isn't it?

Fortunately, you can do this:

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

, , , ascii .

, "unicode" !!!!!!!!!!!

+17

Try:

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

:

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

xml .

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

+2

- xml ( ), ...

docXml = ET.parse('template.xml')
root = docXml.getroot()

, XML, ...

docXml.write("output.xml", encoding="utf-8")
0

.

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

Source: https://habr.com/ru/post/1670903/


All Articles