Mo.be
Mo.be

Reputation: 95

moving images from subdirectories of a directory to a new directory with python

I want to move specific files (in this case image files) of subdirectories of a directory to a new directory. I want to move images frompath/to/dir/subdirs to newpath/to/newdir. every subdirectory of the source directory contains a lot of images.

the photo of the subdirectories is attached. how can I do that?

enter image description here

Upvotes: 0

Views: 310

Answers (1)

Olvin Roght
Olvin Roght

Reputation: 7812

The simplest way to copy directory tree is to use shutil.copytree(). To copy only images we can use ignore argument of this function.

Firstly let's declare source path, destination path and extension of files we want to copy:

src_path = r"path/to/dir/subdirs"
dst_path = r"newpath/to/newdir"
ext_names = ".bmp", ".jpg", ".png"  # you can as much as you want

We need to pass to ignore a callable which will return list of files with different extensions.

It can be a lambda expression:

lambda _, files: [file for file in files if not file.endswith(ext_names)]

Or it can be a regular function:

def ignore_files(_, files):  # first argument contains directory path we don't need
    return [file for file in files if not file.endswith(ext_names)]
# OR
def ignore_files(_, files):
    ignore_list = []
    for file in files:
        if file.endswith(ext_names):
            ignore_files.append(file)
    return ignore_list

So, we just call copytree() and it does the job:

from shutil import copytree
...
copytree(src_path, dst_path, ignore=lambda _, files: [file for file in files if not file.endswith(ext_names)])
# OR
copytree(src_path, dst_path, ignore=ignore_files)

Full code (version with lambda):

from shutil import copytree

src_path = r"path/to/dir/subdirs"
dst_path = r"newpath/to/newdir"
ext_names = ".bmp", ".jpg", ".png"

copytree(src_path, dst_path, ignore=lambda _, files: [file for file in files if not file.endswith(ext_names)])

Upd.

If you need to move files, you can pass shutil.move() to copy_function argument:

from shutil import copytree, move
...
copytree(src_path, dst_path, ignore=lambda _, files: [file for file in files if not file.endswith(ext_names)], copy_function=move)

Upvotes: 1

Related Questions