繁体   English   中英

在Python中将多个zip文件合并为一个zip文件

[英]Merge multiple zip files into a single zip file in Python

我有多个具有相同结构的zip文件 - 它们在根级别包含XML文件。 每个zip文件中的所有文件都是唯一的(zip文件中没有重复文件)。 我需要将所有zip文件中的所有XML文件合并到一个zip文件中(与原始zip文件具有相同的结构)。 关于如何最好地做这个的建议? 谢谢。

这是我能提出的最短版本:

>>> import zipfile as z
>>> z1 = z.ZipFile('z1.zip', 'a')
>>> z2 = z.ZipFile('z2.zip', 'r')
>>> z1.namelist()
['a.xml', 'b.xml']
>>> z2.namelist()
['c.xml', 'd.xml']
>>> [z1.writestr(t[0], t[1].read()) for t in ((n, z2.open(n)) for n in z2.namelist())]
[None, None]
>>> z1.namelist()
['a.xml', 'b.xml', 'c.xml', 'd.xml']
>>> z1.close()

没有测试替代方案,对我来说这是最好的(也可能是最明显的!)解决方案,因为 - 假设两个zip文件包含相同数量的数据,此方法只需要解压缩和重新压缩一半(1个文件) )。

PS:列表理解只是将指令放在控制台的一行上(加快调试速度)。 好的pythonic代码需要一个适当的for循环,因为结果列表没有任何意义......

HTH!

这是我想出来的,感谢@mac。 请注意,当前实现的方式是修改第一个zip文件以包含其他zip文件中的所有文件。

import zipfile as z

zips = ['z1.zip', 'z2.zip', 'z3.zip']

"""
Open the first zip file as append and then read all
subsequent zip files and append to the first one
"""
with z.ZipFile(zips[0], 'a') as z1:
    for fname in zips[1:]:
        zf = z.ZipFile(fname, 'r')
        for n in zf.namelist():
            z1.writestr(n, zf.open(n).read())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM