avatar

Python: Extract Files from All Subfolders

import shutil
from pathlib import Path


def extract_files_from_all_subfolders(filename):
    ROOT = Path(__file__).parent
    for file in ROOT.glob("**/*"):
        # exclude the output folder
        if "output" in str(file):
            continue
        if file.is_dir() and file.name == filename:
            # extract the parent folder of the file to the output folder
            parent_folder = file.parent
            copy_folder_to_folder(file, parent_folder.name)


def copy_folder_to_folder(folder, destination):
    ROOT = Path(__file__).parent
    destination = ROOT / "output" / destination
    destination.mkdir(exist_ok=True)
    shutil.copytree(folder, destination / folder.name)


if __name__ == "__main__":
    files = extract_files_from_all_subfolders("example_file_name")