gpt4 book ai didi

Python 元素树写入新文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:15:02 26 4
gpt4 key购买 nike

您好,我一直在努力解决这个问题,无法完全弄清楚为什么会出现错误。试图将一些基本的 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')

关于Python 元素树写入新文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37713184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com