Unzip zip files in folders and subfolders with python

后端 未结 3 632
一生所求
一生所求 2020-12-09 23:21

I try to unzip 150 zip files. All the zip files as different names, and they all spread in one big folder that divided to a lot of sub folders and sub sub folders.i want to

3条回答
  •  心在旅途
    2020-12-09 23:25

    You could use Path.rglob() to enumerate zip-files recursively and shutil.unpack_archive() to unpack zip files:

    #!/usr/bin/env python3
    import logging
    from pathlib import Path
    from shutil import unpack_archive
    
    zip_files = Path(r"C:\Project\layers").rglob("*.zip")
    while True:
        try:
            path = next(zip_files)
        except StopIteration:
            break # no more files
        except PermissionError:
            logging.exception("permission error")
        else:
             extract_dir = path.with_name(path.stem)
             unpack_archive(str(path), str(extract_dir), 'zip')
    

    It "extract[s] each archive to separate folder with the same name as the original zip file name and also in the same place as the original zip file" e.g., it extracts 'layers/dir/file.zip' archive into 'layers/dir/file' directory.

提交回复
热议问题