复制目录树最简单的方法是使用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,它将返回具有不同扩展名的文件列表。
可以是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)