Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy images in subfolders to another using Python

Tags:

python

copy

image

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


1 Answers

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)
like image 67
blhsing Avatar answered Feb 01 '26 08:02

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!