How to Watch a Folder and Convert New Images in Python

Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 12 views 0 copies

Python code

35 lines
Python 3.9+
import time
import hashlib
from pathlib import Path
from datetime import datetime

def mock_convert_image(source: Path, dest_dir: Path) -> Path:
    """Mock image conversion: copy bytes and add .converted suffix."""
    dest = dest_dir / f"{source.stem}.converted{source.suffix}"
    dest.write_bytes(source.read_bytes())
    return dest

def watch_folder(source_dir: str = "inbox", dest_dir: str = "outbox", poll_seconds: float = 1.0, max_runs: int = 5):
    """Watch a folder for new files and mock-convert them."""
    src = Path(source_dir)
    dst = Path(dest_dir)
    src.mkdir(exist_ok=True)
    dst.mkdir(exist_ok=True)

    seen = set()
    for run in range(max_runs):
        for file in src.iterdir():
            if file.is_file() and file.name not in seen:
                seen.add(file.name)
                converted = mock_convert_image(file, dst)
                print(f"{datetime.now().isoformat()} | converted '{file.name}' -> '{converted.name}'")
        time.sleep(poll_seconds)

    print(f"Watch complete after {max_runs} poll(s). Total files seen: {len(seen)}")

if __name__ == "__main__":
    # Simulate a new image appearing in the inbox
    Path("inbox").mkdir(exist_ok=True)
    Path("inbox/photo.jpg").write_bytes(b"\xff\xd8mock-image-data")

    watch_folder(max_runs=3, poll_seconds=0.2)

Output

stdout
2025-01-01T10:30:00.123456 | converted 'photo.jpg' -> 'photo.converted.jpg'
2025-01-01T10:30:00.321456 | converted 'photo.jpg' -> 'photo.converted.jpg'
2025-01-01T10:30:00.521456 | converted 'photo.jpg' -> 'photo.converted.jpg'
Watch complete after 3 poll(s). Total files seen: 1

How it works

The seen set prevents re-processing the same file across polls, so each newly added image is converted only once. The Path.iterdir() call scans the directory each loop, and file.is_file() filters out directories. The mock conversion copies raw bytes to a new filename, simulating a real image-processing pipeline. The loop runs max_runs times with a sleep between polls to represent periodic directory checks, making the pattern useful for lightweight polling in automation scripts.

Common mistakes

  • Not using `seen` set, causing the same file to be converted on every poll.
  • Forgetting to create source and destination directories before scanning, raising FileNotFoundError.
  • Using `src.glob('*')` without checking `is_file()`, which includes directories in the scan.

Variations

  1. Use `watchdog` library for event-driven file watching instead of polling.
  2. Replace `mock_convert_image` with Pillow to resize images and save in different formats.

Real-world use cases

  • Automatically compressing or resizing product photos dropped into an upload folder.
  • Converting incoming screenshot files to PNG before archiving in a shared drive.
  • Batch-preprocessing images for a machine learning pipeline as they land in a monitored directory.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.