我希望将目录子目录的特定文件(在本例中为图像文件)移动到新目录。我想把图片从path/to/dir/subdirs移到newpath/to/newdir。源目录的每个子目录都包含很多图像。
子目录的照片附后。我怎么能这么做?

发布于 2021-05-19 16:24:12
复制目录树的最简单方法是使用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)])Upd.
如果需要移动文件,可以将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)https://stackoverflow.com/questions/67605993
复制相似问题