首页 > 解决方案 > 使用 Python 将子文件夹中的图像复制到另一个

问题描述

我有一个包含许多子文件夹的文件夹,其中包含图像。我想将这些子文件夹的图像复制到目标文件夹。所有图像都应该在一个文件夹中。使用我当前的代码,Python 将所有子文件夹复制到目标文件夹,但这不是我想要的。我只有 .jpg 图像。我目前的代码是:

dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination" 
for file in os.listdir(dir_src):
    print(file) 
    src_file = os.path.join(dir_src, file)
    dst_file = os.path.join(dir_dst, file)
    shutil.copytree(src_file, dst_file)

我很感激每一个提示

标签: pythonimagecopy

解决方案


您可以使用os.walk

import os
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for root, _, files in os.walk(dir_src):
    for file in files:
        if file.endswith('.jpg'):
            copy(os.path.join(root, file), dir_dst)

或者,glob如果您使用的是 Python 3.5+,则可以使用:

import glob
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for file in glob.iglob('%s/**/*.jpg' % dir_src, recursive=True):
    copy(file, dir_dst)

推荐阅读