python - 使用 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)
我很感激每一个提示
解决方案
您可以使用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)
推荐阅读
- android - java.lang.IllegalStateException:从 androidx.constraintlayout.widget.ConstraintLayout 找不到 ViewTreeLifecycleOwner
- java - HTTP 状态 400 - 错误请求 Spring MVC
- jquery - 使用 ajax 和 laravel 显示数据
- javascript - javascript async await 我不明白它是如何工作的
- azure-machine-learning-service - 从管道注册模型 (CLI v2)
- command-line - 您可以从进程 ID 中获取完整的命令行(包括命令行参数等)吗?
- vba - Jira 自定义字段实名列表
- r - 从图中向下添加标签
- c# - 覆盖 Razor 视图中的变量
- ruby - 使用旧的 ruby 项目构建指南针时出错