【问题标题】:Copy images in subfolders to another using Python使用 Python 将子文件夹中的图像复制到另一个
【发布时间】:2018-09-11 11:46:19
【问题描述】:

我有一个包含许多包含图像的子文件夹的文件夹。我想将这些子文件夹的图像复制到目标文件夹。所有图像都应该在一个文件夹中。使用我当前的代码,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)

我很感激每一个提示

【问题讨论】:

  • 按文件过滤,你可以使用glob只拍jpg图片
  • 感谢您的快速响应!我用 glob 编辑了代码。现在我可以使用此代码找到所有图像。但是如何将这些复制到目标文件夹?

标签: python image copy


【解决方案1】:

你可以使用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)

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

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)

【讨论】:

  • 非常感谢!这段代码解决了我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多