Python Element Tree Writing to New File(Python 元素树写入新文件)
问题描述
所以我一直在努力解决这个问题,但不太明白为什么我会收到错误.试图将一些基本的 XML 导出到一个新文件中,一直给我一个 TypeError.下面是代码的一个小示例
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. Below is a small sample of the code
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 ElementTree.write
method defaults to us-ascii encoding and as such expects a file opened for writing binary:
输出是字符串(str)或二进制(字节).这是由 encoding 参数控制的.如果 encoding 是 unicode"
,则输出是一个字符串;否则,它是二进制的.请注意,如果它是一个打开的文件对象,这可能会与 file 的类型冲突;确保不要尝试将字符串写入二进制流,反之亦然.
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)
或打开文件以文本模式写入并给出unicode"
作为编码:
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')
这篇关于Python 元素树写入新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python 元素树写入新文件
基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01