I'm trying to output an XML structure to stdout with ElementTree. I'm trying with:
root = ET.Element('networkData')
tree = ET.ElementTree(root)
tree.write(sys.stdout)
but I get no output. Changing the argument to a string produces an XML file as expected. Using the debugger (adding encoding tip from SO) I get:
-> tree.write(sys.stdout, encoding='utf-8')
(Pdb) n
TypeError: write() argument must be str, not bytes
Googling the error I get a few hits but none that seems to address this issue. Also, I get confused by the error message as sys.stdout is a _io.TextIOWrapper object.
The problem has to do with encoding. Without correct encoding, the argument is treated as binary and not as string, which explains the error message. The proper write-statement should be:
tree.write(sys.stdout, encoding='unicode')
or
tree.write(sys.stdout.buffer)
as pointed out in the comments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With