[英]Copy specific files from directory and subdirectories into new directory Python
[英]moving images from subdirectories of a directory to a new directory with python
复制目录树最简单的方法是使用shutil.copytree()
。 要仅复制图像,我们可以使用此 function 的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)]
也可以是普通的 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
因此,我们只需调用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.