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

Ben*_* H. 9 python svg elementtree

使用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()
Run Code Online (Sandbox Code Playgroud)

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

Ray*_*oal 18

事实证明,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'>
Run Code Online (Sandbox Code Playgroud)

傻,不是吗?

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

>>> type(tostring(element, encoding="unicode"))
<class 'str'>
Run Code Online (Sandbox Code Playgroud)

是的,我们都认为字节的荒谬和古老的,四十多岁和过时的编码被称为ascii死了.

不要让我开始的事实,他们称之为"unicode"一个编码 !!!!!!!!!!!


小智 7

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

f = open('sample.svg', 'wb')
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试:

f.write(et.tostring(doc).decode(encoding))
Run Code Online (Sandbox Code Playgroud)

例子:

f.write(et.tostring(doc).decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)