pythonshutilcopytree

How to copy a directory structure along with specific file extensions?


I've been trying for days now and searched online for solutions and I only found problems similar to mine which didn't help me. The best I managed so far is to copy the entire structure with all files in it. But I need to copy only .txt and .bmp files.

For my example I have a ChrisO folder and in it a source folder with the subfolders that contain the files. By running the code I need to create the destination folder with the same subfolders and in them all .txt and bmp. files

import os
import shutil
import glob

src= "S:\ChrisO\source"

dest= "S:\ChrisO\destination"

shutil.copytree(src, dest)

Solution

  • I can't currently run the code to try it out, but I think this could work:

    import os
    import shutil
    import glob
    
    src_dir = "S:/ChrisO/source"
    dest_dir = "S:/ChrisO/destination"
    file_extensions = ["txt", "bmp"]
    
    def copy_files_with_extensions(src, dest, extensions):
        for extension in extensions:
            src_files = glob.glob(os.path.join(src, "**", f"*.{extension}"), recursive=True)
            for src_file in src_files:
                dest_file = os.path.join(dest, os.path.relpath(src_file, src))
                os.makedirs(os.path.dirname(dest_file), exist_ok=True)
                shutil.copy(src_file, dest_file)
    
    
    copy_files_with_extensions(src_dir, dest_dir, file_extensions)