python将文件夹中所有子文件夹中的图片统一保存
一个大文件夹中包含许多子文件夹,子文件夹中又包含不同类型的图片,目标:将子文件夹中的图片移动到一个文件夹中,python代码如下:
import os
import shutil
source_folder = '/path/to/source/folder'
destination_folder = '/path/to/destination/folder'
# 自动创建输出目录
if not os.path.exists(destination_folder):
os.makedirs(destination_folder)
# 遍历所有子文件夹
for parent_folder, _, file_names in os.walk(source_folder):
# 遍历当前子文件夹中的所有文件
for file_name in file_names:
# 只处理图片文件
if file_name.endswith(('jpg', 'jpeg', 'png', 'gif')):
# 构造源文件路径和目标文件路径
source_path = os.path.join(parent_folder, file_name)
destination_path = os.path.join(destination_folder, file_name)
# 复制文件到目标文件夹
shutil.copy(source_path, destination_path)