python - 编写 gzip 格式压缩的 ElementTree

标签 python gzip elementtree

我正在尝试以 gzip 格式编写 xml 的特定子树。以下 Python 代码将常规 xml 写入文件,但我不确定如何为其添加压缩

import os, time, gzip
import xml.etree.cElementTree as ET
from xml.etree.cElementTree import ElementTree

. . . 

ElementTree(child).write('outputFile.xml')      

我想编写一个可以用常见应用程序打开的文件outputFile.xml.gz。请记住,我是 Python 新手...

最佳答案

ElementTree.write() 可以传递一个打开用于写入的文件对象。

import os, time, gzip
import xml.etree.cElementTree as ET
from xml.etree.cElementTree import ElementTree

. . . 

f = gzip.open('/home/joe/file.txt.gz', 'wb')
ElementTree(child).write(f) 
f.close()

来自http://docs.python.org/2/library/gzip.htmlhttp://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree .

关于python - 编写 gzip 格式压缩的 ElementTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202516/

相关文章:

python - Graphite 作为 Django Web 应用程序为所有静态资源返回 404

python - 使用 API REST 创建的 GitHub secret 但返回空

webpack - gzip 和 webpack 压缩

python - 检查并删除 XML 中重复的子标签

Python 2.5.4 - ImportError : No module named etree. ElementTree

python - py2neo 缓存在烧我吗?

python - 避免将 DLL 放入 CWD

azure - 如何使用 Azure 数据工厂 GUI 将多个 blob 文件压缩到一个 .gzip 中?

amazon-web-services - AWS Api网关代理压缩 "invalid block type"

python - 有没有使用元素树从 xml 文件创建多个数据框的方法?