Under the file path D:/src, I have images folders and its subfolders which have a regular structure as follows:
Folder A - Subfolder a - Subfolder b - Subfolder c Folder B - Subfolder a - Subfolder b - Subfolder c - Subfolder d Folder C - Subfolder a - Subfolder b - Subfolder c ...
I want to copy all .jpg files in Subfolder b from Folder A, B, C and so on to a new folder Subfolder b in D:/dst. How can I do it in Python? Thanks.
Subfolder b -xxx.jpg -xyx.jpg -yxz.jpg ...
Here is what I have found from the following link may helps:
Copy certain files from one folder to another using python
import os; import shutil; import glob; source="C:/Users/X/Pictures/test/Z.jpg" dest="C:/Users/Public/Image" if os.path.exists(dest): print("this folder exit in this dir") else: dir = os.mkdir(dest) for file in glob._iglob(os.path.join(source),""): shutil.copy(file,dest) print("done")
Advertisement
Answer
Try this
import os from os.path import join, isfile BASE_PATH = 'd:/test' SUBFOLDER = 'Subfolder b' for folder, subfolders, *_ in os.walk(BASE_PATH): if SUBFOLDER in subfolders: full_path = join(BASE_PATH, folder, SUBFOLDER) files = [f for f in os.listdir(full_path) if isfile(join(full_path, f)) and f.lower().endswith(('.jpg', '.jpeg'))] for f in files: file_path = join(full_path, f) print (f'Copy {f} somewehere')