Unzip nested zip files in python

后端 未结 6 1163
庸人自扰
庸人自扰 2020-12-01 17:07

I am looking for a way to unzip nested zip files in python. For example, consider the following structure (hypothetical names for ease):

  • Folder
    • Zipfi
6条回答
  •  伪装坚强ぢ
    2020-12-01 17:40

    This works for me. Just place this script with the nested zip under the same directory. It will also count the total number of files within the nested zip as well

    import os
    
    from zipfile import ZipFile
    
    
    def unzip (path, total_count):
        for root, dirs, files in os.walk(path):
            for file in files:
                file_name = os.path.join(root, file)
                if (not file_name.endswith('.zip')):
                    total_count += 1
                else:
                    currentdir = file_name[:-4]
                    if not os.path.exists(currentdir):
                        os.makedirs(currentdir)
                    with ZipFile(file_name) as zipObj:
                        zipObj.extractall(currentdir)
                    os.remove(file_name)
                    total_count = unzip(currentdir, total_count)
        return total_count
    
    total_count = unzip ('.', 0)
    print(total_count)
    

提交回复
热议问题