Python Element Tree Writing to New File

The ElementTree.write method defaults to us-ascii encoding and as such expects a file opened for writing binary:

The output is either a string (str) or binary (bytes). This is controlled by the encoding argument. If encoding is "unicode", the output is a string; otherwise, it’s binary. Note that this may conflict with the type of file if it’s an open file object; make sure you do not try to write a string to a binary stream and vice versa.

So either open the file for writing in binary mode:

with open('person.xml', 'wb') as f:
    tree.write(f)

or open the file for writing in text mode and give "unicode" as encoding:

with open('person.xml', 'w') as f:
    tree.write(f, encoding='unicode')

or open the file for writing in binary mode and pass an explicit encoding:

with open('person.xml', 'wb') as f:
    tree.write(f, encoding='utf-8')

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)