如何用os.walk和PIL保存编辑后图片并保留原目录结构?
修复方案:保留目录结构批量处理图片
核心修复逻辑
问题根源在于没有正确建立输入文件相对目录与输出目录的映射关系。解决关键是提取每个文件相对于输入根目录的路径,以此构建对应输出子目录,确保结构完全匹配原目录。
完整修复代码
from PIL import Image import os def process_images(input_dir, output_dir, edit_func): if not os.path.isdir(input_dir): raise ValueError("输入目录不存在") # 遍历输入目录下所有文件(包含子目录) for root, _, files in os.walk(input_dir): # 获取当前目录相对于输入根目录的路径 relative_path = os.path.relpath(root, input_dir) # 构建对应的输出子目录路径 output_subdir = os.path.join(output_dir, relative_path) # 创建输出子目录(已存在则跳过) os.makedirs(output_subdir, exist_ok=True) for file in files: # 筛选图片格式文件(可按需扩展后缀) if file.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')): input_file = os.path.join(root, file) output_file = os.path.join(output_subdir, file) try: with Image.open(input_file) as img: edited_img = edit_func(img) edited_img.save(output_file) except Exception as e: print(f"处理 {input_file} 失败: {str(e)}") continue # 示例编辑函数:转为灰度图(可替换为你的自定义编辑逻辑) def grayscale_edit(img): return img.convert('L') # 使用示例 if __name__ == "__main__": INPUT_DIR = "./source_images" OUTPUT_DIR = "./processed_images" process_images(INPUT_DIR, OUTPUT_DIR, grayscale_edit)
关键修复点说明
- 相对路径映射:
os.path.relpath(root, input_dir)精准获取当前文件所在目录与输入根目录的相对位置,保证输出目录结构和输入完全一致 - 自动创建子目录:
os.makedirs(output_subdir, exist_ok=True)自动生成所需子目录,无需手动判断路径是否存在 - 规范路径拼接:全程使用
os.path.join拼接路径,避免字符串拼接导致的跨平台路径格式错误 - 容错处理:捕获图片处理异常,单个文件处理失败不会中断整个批量任务
内容的提问来源于stack exchange,提问作者Zairi
相关产品推荐
相关产品推荐

