Python Element Tree Writing to New File

前端 未结 1 1751
野趣味
野趣味 2021-01-02 17:13

Hi so I\'ve been struggling with this and can\'t quite figure out why I\'m getting errors. Trying to export just some basic XML into a new file, keeps giving me a TypeError.

相关标签:
1条回答
  • 2021-01-02 17:20

    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:

    tree.write(open('person.xml', 'wb'))
    

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

    tree.write(open('person.xml', 'w'), encoding='unicode')
    
    0 讨论(0)
提交回复
热议问题