Python 元素树写入新文件

标签 python xml tree element

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

相关文章:

javascript - 根据深度值在对象树中搜索

python - 绘制嵌套的 networkx 图

javascript - EXTJS4 - 对于 TreeStore,如何传递参数和操作方法?

通过串口与 Arduino 接口(interface)的 Python 代码无法在 Raspberry Pi 上运行

java - Xades4j验证封装签名

xml - 使用 XSLT/XPath,如何匹配 null namespace 中的任何元素?

php - 使用 eBay API 使用 PHP 获取我的 eBay 列表

python - 累积分布图python

python - 计算 pandas 数据框中的路径数据

python - html 模板中的 Django for 循环不显示