Reputation: 33511
I am using ElementTree
to create, parse and modify XML files and object. I am creating the tree like this:
import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
then, I want to write this to a file. According to the documentation, I should use an ElementTree
object for that, but how to create that from the Element
?
I tried
e = etree.ElementTree(foo)
e.write(filename)
but that doesn't work:
TypeError: must be str, not bytes
Upvotes: 3
Views: 2448
Reputation: 473853
Your opened file should be opened with b
(binary) flag:
import xml.etree.ElementTree as etree
foo = etree.Element("root")
etree.SubElement(foo, "extra", { "id": "50" })
e = etree.ElementTree(foo)
with open('test.xml', 'wb') as f:
e.write(f)
or just pass a filename/path to write()
:
e.write('test.xml')
Upvotes: 2