在 Python 中将多个 zip 文件合并为一个 zip 文件 [英] Merge multiple zip files into a single zip file in Python

查看:93
本文介绍了在 Python 中将多个 zip 文件合并为一个 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个具有相同结构的 zip 文件——它们包含根级别的 XML 文件.每个 zip 文件中的所有文件都是唯一的(在 zip 文件中没有重复).我需要将所有 zip 文件中的所有 XML 文件合并为一个 zip 文件(与原始 zip 文件具有相同的结构).有关如何最好地执行此操作的建议?谢谢.

解决方案

这是我能想到的最短版本:

<预><代码>>>>将 zipfile 导入为 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())][无,无]>>>z1.namelist()['a.xml', 'b.xml', 'c.xml', 'd.xml']>>>z1.close()

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

PS:列表理解只是为了将指令保留在控制台的一行上(这可以加快调试速度).考虑到结果列表没有任何用途......

HTH!

I have multiple zip files that have the same structure -- they contain XML files at the root level. All files in each zip file are unique (no duplicates across the zip files). I need to combine all of the XML files from all of the zip files into a single zip file (with the same structure as the original zip files). Suggestions for how to best go about doing this? Thanks.

解决方案

This is the shortest version I could come up with:

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

Without testing the alternative, to me this is the best (and probably most obvious too!) solution because - assuming both zip files contains the same amount of data, this method requires the decompression and re-compression of only half of it (1 file).

PS: List comprehension is there just to keep instructions on one line in the console (which speeds debugging up). Good pythonic code would require a proper for loop, given that the resulting list serves no purpose...

HTH!

这篇关于在 Python 中将多个 zip 文件合并为一个 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆