Merge multiple zip files into a single zip file in Python

前端 未结 2 2135
暗喜
暗喜 2021-02-19 05:42

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

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-19 06:34

    Here's what I came up with, thanks to @mac. Note that the way this is currently implemented the first zip file is modified to contain all the files from the other zip files.

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

提交回复
热议问题