使用 python 将图像从目录的子目录移动到新目录

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

我想将目录子目录的特定文件(在本例中为图像文件)移动到新目录。我想将图像从 path/to/dir/subdirs 移动到 newpath/to/newdir。源目录的每个子目录都包含很多图像。

附上子目录的照片。 我该怎么做?

复制目录树最简单的方法是使用shutil.copytree()。要仅复制图像,我们可以使用此函数的 ignore 参数。

首先让我们声明要复制的文件的源路径、目标路径和扩展名:

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

我们需要向 ignore 传递一个可调用函数,它将 return 具有不同扩展名的文件列表。

可以是lambda表达式:

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

也可以是普通函数:

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

所以,我们只需调用 copytree() 即可完成工作:

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)

完整代码(带 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)])

更新

如果需要移动文件,可以将shutil.move()传给copy_function参数:

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)