Python 元素树写入新文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37713184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Element Tree Writing to New File
提问by Kyle Zimmerman
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
嗨,所以我一直在努力解决这个问题,无法弄清楚为什么我会收到错误。试图将一些基本的 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'))
回答by Ilja Everil?
The ElementTree.write
method defaults to us-ascii encoding and as such expects a file opened for writing binary:
该ElementTree.write
方法默认为 us-ascii 编码,因此需要打开一个用于写入二进制文件的文件:
The output is either a string (str) or binary (bytes). This is controlled by the encoding argument. If encodingis
"unicode"
, the output is a string; otherwise, it's binary. Note that this may conflict with the type of fileif it's an open file object; make sure you do not try to write a string to a binary stream and vice versa.
输出是字符串(str)或二进制(字节)。这是由 encoding 参数控制的。如果encoding是
"unicode"
,则输出是一个字符串;否则,它是二进制的。请注意,如果它是一个打开的文件对象,这可能与文件类型冲突;确保您不要尝试将字符串写入二进制流,反之亦然。
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:
或打开文件以文本方式编写,并给"unicode"
作为编码:
tree.write(open('person.xml', 'w'), encoding='unicode')