This is modified from the general recursive solution here: https://stackoverflow.com/a/54544211/42346 to, more specifically, copy/move files with a given extension from one directory to another whilst preserving subdirectories.
I'm reluctant to use .rename()
for this purpose as it seems slightly less intuitive than copying or moving.
Any other ideas you have about how to clean this up are greatly appreciated.
import os, shutil
from pathlib import Path
def recur(path,destination,file_ext,is_subdir=False):
if not is_subdir:
os.chdir(path)
for entry in os.scandir(path):
if os.path.splitext(entry.name)[-1].lower() == file_ext:
subdir_path = entry.path.replace(os.getcwd() + os.sep,'')
new_path = Path(destination) / subdir_path
os.makedirs(os.path.dirname(new_path), exist_ok=True)
shutil.copy(entry.path,new_path)
if entry.is_dir():
recur(Path(path).joinpath(entry.name),destination,file_ext,is_subdir=True)