You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取主目录下多子文件夹图片?含resize等处理需求

遍历子文件夹并批量处理图片的解决方案

Hey there! Sounds like you had a rough time getting pathlib to work for your directory structure—let's fix that and build a solid workflow for resizing, cropping, and processing your images.

First, let's align on your setup: a main directory with multiple subfolders, each holding exactly two images. We'll use pathlib (it's actually perfect for this once you nail the traversal logic) combined with Pillow for all image manipulation tasks.

Step 1: Install Required Libraries

If you haven't already, install Pillow for image processing—this is the go-to library for tasks like resize and crop:

pip install pillow

Step 2: Correct Pathlib Traversal Logic

The most common pitfall with pathlib is either not targeting subfolders correctly or failing to filter for image files. Here's how to iterate through each subfolder and grab every image inside:

from pathlib import Path
from PIL import Image

# Replace with your actual main directory path
main_dir = Path("/path/to/your/main/directory")

# Iterate over all items in the main directory, only pick subfolders
for subfolder in main_dir.iterdir():
    if subfolder.is_dir():
        # Grab all JPG and PNG files in the subfolder (add other extensions if needed)
        image_files = list(subfolder.glob("*.jpg")) + list(subfolder.glob("*.png"))
        
        # Loop through each image in the subfolder
        for img_path in image_files:
            # Open the image (using a context manager to auto-close it)
            with Image.open(img_path) as img:
                print(f"Processing {img_path.name} in {subfolder.name}")
                # Your processing steps go here—we'll add examples next

Step 3: Add Resize & Crop Operations

Let's build a helper function to handle resizing and cropping, then integrate it into the loop. We'll also add logic to save processed images (you can save them back to the same subfolder or a dedicated output directory):

def process_image(img: Image.Image, target_size: tuple = (512, 512)) -> Image.Image:
    # Resize the image while preserving aspect ratio
    img.thumbnail(target_size)
    
    # Center crop to the exact target size (skip this if you don't need cropping)
    width, height = img.size
    left = (width - target_size[0]) // 2
    top = (height - target_size[1]) // 2
    right = left + target_size[0]
    bottom = top + target_size[1]
    
    cropped_img = img.crop((left, top, right, bottom))
    return cropped_img

# Update the main loop to use the processing function
for subfolder in main_dir.iterdir():
    if subfolder.is_dir():
        image_files = list(subfolder.glob("*.jpg")) + list(subfolder.glob("*.png"))
        
        # Optional: Create a subfolder to store processed images (avoids overwriting originals)
        processed_dir = subfolder / "processed"
        processed_dir.mkdir(exist_ok=True)
        
        for img_path in image_files:
            try:
                with Image.open(img_path) as img:
                    processed_img = process_image(img, target_size=(512, 512))
                    
                    # Save the processed image with a clear suffix
                    save_path = processed_dir / f"processed_{img_path.name}"
                    processed_img.save(save_path)
                    print(f"Saved processed image to {save_path}")
            except Exception as e:
                print(f"Failed to process {img_path}: {str(e)}")

Key Tips to Avoid Headaches

  • Filter for All Image Types: If your images use .jpeg, .webp, or other formats, add those to the glob calls (e.g., subfolder.glob("*.webp")).
  • Error Handling: The try-except block catches corrupted images or unexpected file types—critical for avoiding crashes mid-process.
  • Pathlib Benefits: Using Path objects means you don't have to worry about OS-specific path separators (Windows backslashes vs. macOS/Linux slashes)—it handles that automatically.

This setup should work seamlessly for your directory structure. If you hit any specific snags, just tweak the processing function or traversal logic to fit your needs!

内容的提问来源于stack exchange,提问作者Pankaj Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:26:25