【问题标题】:moving images from subdirectories of a directory to a new directory with python使用python将图像从目录的子目录移动到新目录
【发布时间】:2021-08-08 20:36:12
【问题描述】:

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

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

【问题讨论】:

  • 任何代码尝试?
  • 是的,我尝试过 os.walk、os.listdir(os.path.join)、shutil.move 方法,但他们没有给我想要的解决方案@ShawnRamirez
  • @Mo.be,您只需要移动跳过其他文件的图像吗?
  • 是的,我只需要子目录中的图像。 @OlvinR​​oght

标签: python directory subdirectory


【解决方案1】:

复制目录树最简单的方法是使用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)

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2017-07-29
    相关资源
    最近更新 更多