繁体   English   中英

ElementTree TypeError“write()参数必须是str,而不是Python3中的字节”

[英]ElementTree TypeError “write() argument must be str, not bytes” in Python3

使用Python3和ElementTree生成.SVG文件时出现问题。

    from xml.etree import ElementTree as et
    doc = et.Element('svg', width='480', height='360', version='1.1', xmlns='http://www.w3.org/2000/svg')

    #Doing things with et and doc

    f = open('sample.svg', 'w')
    f.write('<?xml version=\"1.0\" standalone=\"no\"?>\n')
    f.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n')
    f.write('\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n')
    f.write(et.tostring(doc))
    f.close()

Function et.tostring(doc)生成TypeError“write()参数必须是str,而不是bytes”。 我不明白这种行为,“et”应该将ElementTree-Element转换为字符串? 它适用于python2,但不适用于python3。 我做错了什么?

事实证明, tostring尽管它的名字 ,确实返回一个类型为bytes的对象。

发生了奇怪的事情。 无论如何,这是证据:

>>> from xml.etree.ElementTree import ElementTree, tostring
>>> import xml.etree.ElementTree as ET
>>> element = ET.fromstring("<a></a>")
>>> type(tostring(element))
<class 'bytes'>

傻,不是吗?

幸运的是,你可以这样做:

>>> type(tostring(element, encoding="unicode"))
<class 'str'>

是的,我们都认为字节的荒谬和那个古老的,四十多岁和过时的编码ascii已经死了。

并且不要让我开始称他们称"unicode"编码 !!!!!!!!!!!

尝试:

f.write(et.tostring(doc).decode(encoding))

例:

f.write(et.tostring(doc).decode("utf-8"))

在写入xml文件时指定字符串的编码。

像使用write() decode(UTF-8) write() 示例: file.write(etree.tostring(doc).decode(UTF-8))

对我来说,最简单的方法是首先创建一些模板xml(只是定义根),然后解析它......

docXml = ET.parse('template.xml')
root = docXml.getroot()

然后在我的xml中做我想做的事情并打印出来......

docXml.write("output.xml", encoding="utf-8")

输出文件应该是二进制模式。

f = open('sample.svg', 'wb')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM