创建zipfile:TypeError:类型为' ElementTree'的对象没有len()

时间:2016-08-15 09:18:27

标签: python xml elementtree zipfile

我正在将xml数据写入zip。

from xml.etree.ElementTree import Element, SubElement, ElementTree
from zipfile import ZipFile

def create_tree():
    root = Element("root")
    doc = SubElement(root, "doc")
    SubElement(doc, "field", name="blah").text = "text"

    return ElementTree(root)


def test():
    """
    Create zip
    """
    with ZipFile("xml.zip", 'w') as ziparc:
        element_tree = create_tree()
        ziparc.writestr("file.xml", element_tree)


if __name__ == "__main__":
    test()

错误:

File "main_test2_2.py", line 168, in test
    ziparc.writestr('file.xml', element_tree)
  File "/usr/lib/python2.7/zipfile.py", line 1127, in writestr
    zinfo.file_size = len(bytes)            # Uncompressed size
TypeError: object of type 'ElementTree' has no len()

请告诉我,如何将xml数据写入档案?

1 个答案:

答案 0 :(得分:2)

将元素写入假文件(缓冲区)

from xml.etree.ElementTree import Element, SubElement, ElementTree
from zipfile import ZipFile
from io import BytesIO

def create_tree():
    root = Element("root")
    doc = SubElement(root, "doc")
    SubElement(doc, "field", name="blah").text = "text"

    return ElementTree(root)


def test():
    """
    Create zip
    """
    with ZipFile("xml.zip", 'w') as ziparc:
        element_tree = create_tree()
        outbuf = BytesIO()
        element_tree.write(outbuf)
        ziparc.writestr("file.xml", outbuf.getvalue())


if __name__ == "__main__":
    test()

编辑:其他用户尝试建议使用tostring方法,但该方法并不完整&不工作可能是因为首先参数必须是Element而不是ElementTree,因为导入(ElementTree是一个包和一个子类,因此存在歧义)。

然而,我重写了完整的资源并且它也有效,我认为它甚至是一个更好的解决方案(为其他用户删除了他的帖子欢呼!)

from xml.etree.ElementTree import Element, SubElement
from zipfile import ZipFile
import xml.etree.ElementTree

def create_tree():
    root = Element("root")
    doc = SubElement(root, "doc")
    SubElement(doc, "field", name="blah").text = "text"

    return root


def test():
    """
    Create zip
    """
    with ZipFile("xml.zip", 'w') as ziparc:
        element_tree = create_tree()

        ziparc.writestr("file.xml", xml.etree.ElementTree.tostring(element_tree))


if __name__ == "__main__":
    test()