【问题标题】:ElementTree TypeError "write() argument must be str, not bytes" in Python3Python3中的ElementTree TypeError“write()参数必须是str,而不是字节”
【发布时间】:2017-07-17 18:04:22
【问题描述】:

使用 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) 生成类型错误“write() 参数必须是 str,而不是字节”。我不明白这种行为,“et”应该将 ElementTree-Element 转换为字符串吗?它适用于python2,但不适用于python3。我做错了什么?

【问题讨论】:

  • 您查看文档了吗?请参阅 this page 并搜索 tostring。这有帮助吗?
  • 不是真的,应该已经解码成utf-8字节串了,不过python3好像有问题

标签: python svg elementtree


【解决方案1】:

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

f = open('sample.svg', 'wb')

【讨论】:

    【解决方案2】:

    对我来说,首先创建一些模板 xml(只是定义根)然后解析它是最简单的......

    docXml = ET.parse('template.xml')
    root = docXml.getroot()
    

    然后在我的 xml 中做我想做的事情,然后他们打印出来......

    docXml.write("output.xml", encoding="utf-8")
    

    【讨论】:

      【解决方案3】:

      在写入 xml 文件时指定字符串的编码。

      喜欢decode(UTF-8)write()。 示例:file.write(etree.tostring(doc).decode(UTF-8))

      【讨论】:

        【解决方案4】:

        事实证明,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)) 的结果时,我简直不敢相信。然后看到结果由于参数值的变化而变化。哇。那真的很奇怪。好问题。
        【解决方案5】:

        试试:

        f.write(et.tostring(doc).decode(encoding))
        

        例子:

        f.write(et.tostring(doc).decode("utf-8"))
        

        【讨论】:

          猜你喜欢
          • 2020-12-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-15
          • 2018-04-12
          • 2016-11-26
          相关资源
          最近更新 更多