Reacting to File Changes with Python and Watchdog
Table of Contents
Sometimes you want to run code automatically when files change, like rebuild assets, trigger a script, or just keep an eye on what’s happening in a directory.
Instead of constantly polling or writing your own file watcher, Python’s watchdog library makes this painless.
How it works under the hood
Operating systems already provide mechanisms to signal when files change:
- Linux: inotify
- macOS: FSEvents
- Windows: ReadDirectoryChangesW
Watchdog doesn’t reinvent the wheel. It wraps these low-level APIs in a Python layer, normalizes the events, and hands them to you via a callback system. This means:
- No polling loop that keeps re-stat’ing files.
- Immediate events (create, modify, delete, move).
- Cross-platform code that feels the same everywhere.
Setup
Install watchdog with pip:
pip install watchdog
Example
Here’s a minimal script that watches the current directory for file changes:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
if not event.is_directory:
print(f"File modified: {event.src_path}")
def on_created(self, event):
if not event.is_directory:
print(f"File created: {event.src_path}")
def on_deleted(self, event):
if not event.is_directory:
print(f"File deleted: {event.src_path}")
if __name__ == "__main__":
path = "." # directory to watch
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
print(f"Watching for changes in: {path}")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Save it as watchdog_example.py and run:
python watchdog_example.py
Now, when you create, edit, or delete a file in the same directory, it will print an event.
Example:
File created: /home/sven/foo.txt
File modified: /home/sven/foo.txt
File deleted: /home/sven/foo.txt
What’s happening in this script?
Observer: a background thread that hooks into inotify/FSEvents/etc.schedule(): tells the observer which directory to watch, and which handler to call on events.FileSystemEventHandler: a base class with methods (on_created,on_modified, etc.). We subclass it and override what we need.- Loop with
sleep(1): keeps the script alive while the observer thread listens for OS events.
When the OS reports a file system event, watchdog translates it into a Python FileSystemEvent and calls the corresponding handler.
Use cases
A few things you can automate with this:
- Automatically run tests when source files change
- Live-reloading web servers during development
- File syncing scripts (copy changed files to a backup or VM)
- Lightweight monitoring (alert if a file gets deleted or overwritten)
Wrap up
watchdog is a tiny but powerful tool that saves you from reinventing the wheel.
Next time you need something to react to file changes, drop this in and hack away.