Python Element Tree Writing to New File

时间秒杀一切 提交于 2019-12-12 09:00:01

问题


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'))

回答1:


The ElementTree.write method defaults to us-ascii encoding and as such expects a file opened for writing binary:

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:

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

or open the file for writing in text mode and give "unicode" as encoding:

tree.write(open('person.xml', 'w'), encoding='unicode')


来源:https://stackoverflow.com/questions/37713184/python-element-tree-writing-to-new-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!