在Python3中,ElementTree TypeError“write()参数必须是str,而不是bytes”

2024-04-28 06:44:09 发布

您现在位置:Python中文网/ 问答频道 /正文

用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中无效。我做错了什么?


Tags: svgorghttpdocversionwwwxmlpython3
3条回答

尝试:

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))

事实证明,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'>

是的,我们都认为字节的荒谬,而那个古老的、40多年前的、过时的编码ascii已经死了。

别让我开始说他们叫"unicode"一个编码!!!!!!!!!!!

相关问题 更多 >