user10347172
user10347172

Reputation:

Copy images in subfolders to another using Python

I have a folder with many subfolders that contains images. I want to copy these images of the subfolders to the destination folder. All images should be in one folder. With my current code, Python copies all subfolders to the destination folder, but thats not what I want. I only what the .jpg images. My current code is:

dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination" 
for file in os.listdir(dir_src):
    print(file) 
    src_file = os.path.join(dir_src, file)
    dst_file = os.path.join(dir_dst, file)
    shutil.copytree(src_file, dst_file)

I'm grateful for every tip

Upvotes: 3

Views: 1979

Answers (1)

blhsing
blhsing

Reputation: 106523

You can use os.walk:

import os
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for root, _, files in os.walk(dir_src):
    for file in files:
        if file.endswith('.jpg'):
            copy(os.path.join(root, file), dir_dst)

or you can use glob if you're using Python 3.5+:

import glob
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for file in glob.iglob('%s/**/*.jpg' % dir_src, recursive=True):
    copy(file, dir_dst)

Upvotes: 2

Related Questions