在Python3中,ElementTree TypeError“write()参数必须是str,而不是字节”
在使用Python3和ElementTree生成.SVG文件时遇到了问题。在Python3中,ElementTree TypeError“write()参数必须是str,而不是字节”
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()
的作用et.tostring(文件)生成类型错误 “写()参数必须海峡,不是字节”。我不明白这种行为,“et”应该将ElementTree元素转换为字符串?它适用于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"
的编码 !!!!!!!!!!!
测试结果很有趣。当我看到'type(tostring(element))'的结果时,我无法相信它。然后看到结果因参数值的变化而改变。哇。那真的很奇怪。很好的问题。 –
尝试:
f.write(et.tostring(doc).decode(encoding))
例子:
f.write(et.tostring(doc).decode("utf-8"))
在写入xml文件时指定字符串的编码。
像decode(UTF-8)
与write()
。 例如:file.write(etree.tostring(doc).decode(UTF-8))
您是否检查过文档?查看[本页](https://docs.python.org/3/library/xml.etree.elementtree.html)并搜索'tostring'。这有帮助吗? –
不是真的,它应该已经在utf-8字节串中解码,但是python3似乎有问题 –