AI & Python Developer

All posts

Building a File‑Watcher Automation with Python’s Watchdog

3 min read

  • python
  • automation
  • watchdog
  • file-processing

When you work with data pipelines or a simple upload folder, you often need to run a script every time a new file appears. Manually checking the directory is tedious and error‑prone. In this post I’ll show you how to set up a lightweight file‑watcher in Python that reacts instantly to new files and runs any processing you define.

Why a file‑watcher?

  • Immediate feedback – Process files as soon as they land.
  • No polling – Avoid wasteful loops that check the folder every few seconds.
  • Cross‑platform – Works on Windows, macOS, and Linux.

Install the watchdog package

pip install watchdog

Watchdog is a thin wrapper around OS‑level file‑system events. The API is stable, but check the official docs for version‑specific notes.

Basic concepts

  • Observer – Runs in the background and watches one or more paths.
  • EventHandler – A class where you define what to do on create, modify, delete, etc.

Step‑by‑step implementation

1. Create a custom handler

# handler.py
from watchdog.events import FileSystemEventHandler
import pathlib

class NewFileHandler(FileSystemEventHandler):
    """Runs when a new file is created in the watched folder."""
    def on_created(self, event):
        # Ignore directories
        if event.is_directory:
            return
        path = pathlib.Path(event.src_path)
        print(f"New file detected: {path.name}")
        # Call your processing function here
        process_file(path)

The on_created method is called automatically for every new file.

2. Write the processing function

# processor.py
def process_file(path):
    """Example: read a CSV and print its first line."""
    if path.suffix.lower() != ".csv":
        print("Skipping non‑CSV file.")
        return
    with path.open("r") as f:
        first_line = f.readline().strip()
    print(f"First line of {path.name}: {first_line}")

You can replace the body with any logic – image resizing, database import, etc.

3. Set up the observer

# watch.py
import time
from pathlib import Path
from watchdog.observers import Observer
from handler import NewFileHandler

WATCH_DIR = Path("./incoming")   # folder to monitor

if __name__ == "__main__":
    WATCH_DIR.mkdir(exist_ok=True)   # ensure folder exists
    event_handler = NewFileHandler()
    observer = Observer()
    observer.schedule(event_handler, str(WATCH_DIR), recursive=False)
    observer.start()
    print(f"Watching {WATCH_DIR.resolve()} for new files...")

    try:
        while True:
            time.sleep(1)   # keep the script alive
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

Run python watch.py and drop a CSV file into the incoming folder. The script prints the file name and its first line instantly.

Running as a background service

  • On Linux/macOS, use nohup python watch.py & or create a systemd service.
  • On Windows, you can register the script with Task Scheduler to start at login.

Common pitfalls and tips

  • File lock race – Some programs write large files in chunks. Add a short time.sleep before processing, or check file size stability.
  • Recursive watching – Set recursive=True if you need sub‑folders, but be aware of extra events.
  • Performance – For very high event rates, batch events or debounce with a timer.

Extending the watcher

  • Multiple handlers – Use different handlers for .txt, .json, etc.
  • Move processed files – After processing, move the file to an archive folder to avoid re‑processing.
  • Integrate with AI – Feed new text files into a language model for summarization automatically.

Key takeaways

  • Watchdog lets you react to file‑system changes without polling.
  • A small FileSystemEventHandler subclass defines the actions you need.
  • Combine the watcher with any Python code – data cleaning, model inference, or API calls – to build fully automated pipelines.