用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,而不是bytes”。我不理解这种行为,“et”应该将ElementTree元素转换为字符串吗?在Python2中有效,但在Python3中无效。我做错了什么?
尝试:
示例:
在写入xml文件时指定字符串的编码。
就像
decode(UTF-8)
和write()
。 示例:file.write(etree.tostring(doc).decode(UTF-8))
事实证明,
tostring
,尽管它的名字是,但实际上确实返回了一个类型为bytes
的对象。奇怪的事情发生了。不管怎样,这是证据:
真傻,不是吗?
幸运的是你可以做到:
是的,我们都认为字节的荒谬,而那个古老的、40多年前的、过时的编码
ascii
已经死了。别让我开始说他们叫
"unicode"
一个编码!!!!!!!!!!!相关问题 更多 >
编程相关推荐