问题描述
遇到了使用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()
函数et.tostring(doc)生成TypeError"write()参数必须为str,而不是字节".我不了解这种行为,"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
的古老,已有40多年历史的过时编码了.
不要让我开始,因为他们称"unicode"
为编码!
Got a Problem with generating a .SVG File with Python3 and ElementTree.
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()
The Function et.tostring(doc) generates the TypeError "write() argument must be str, not bytes". I don't understand that behavior, "et" should convert the ElementTree-Element into a string? It works in python2, but not in python3. What did i do wrong?
As it turns out, tostring
, despite its name, really does return an object whose type is bytes
.
Stranger things have happened. Anyway, here's the proof:
>>> from xml.etree.ElementTree import ElementTree, tostring
>>> import xml.etree.ElementTree as ET
>>> element = ET.fromstring("<a></a>")
>>> type(tostring(element))
<class 'bytes'>
Silly, isn't it?
Fortunately you can do this:
>>> type(tostring(element, encoding="unicode"))
<class 'str'>
Yes, we all thought the ridiculousness of bytes and that ancient, forty-plus-year-old-and-obsolete encoding called ascii
was dead.
And don't get me started on the fact that they call "unicode"
an encoding!!!!!!!!!!!
这篇关于ElementTree TypeError"write()参数必须是str,而不是字节"在Python3中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!