Python 元素树写入新文件

Python Element Tree Writing to New File

您好,我一直在努力解决这个问题,但不太明白为什么会出现错误。试图将一些基本的 XML 导出到一个新文件中,总是给我一个 TypeError。下面是一小段代码示例

from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
import xml.etree.ElementTree as ET


root = Element('QuoteWerksXML')
tree = ElementTree(root)
ver = SubElement(root, "AppVersionMajor")
ver.text = '5.1'

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

ElementTree.write 方法默认为 us-ascii 编码,因此需要打开一个用于写入二进制文件的文件:

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.

所以要么以二进制模式打开文件写入:

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

或以文本模式打开文件写入并给"unicode"作为编码:

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

或者以二进制模式打开文件写入并传递显式编码:

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