Skip to content

Monitoring File System Changes (Watchdog)

diagram what a file-watcher actually delivers mermaid
A watcher reports operating-system events, and those do not map one-to-one onto the things a person means. Saving a file in an editor often arrives as several events, an atomic save arrives as a create-and-move rather than a modify, and events can fire while the file is still being written. Every robust handler debounces and retries.

watchdog lets you react to:

  • file created
  • file modified
  • file deleted

This is useful for:

  • auto-processing new files
  • syncing folders
watchdog_example.py
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
 
 
class Handler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return
        print("created:", event.src_path)
 
 
if __name__ == "__main__":
    import time
 
    path = "."
    observer = Observer()
    observer.schedule(Handler(), path=path, recursive=True)
    observer.start()
 
    print("watching", path)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
 
    observer.join()
  • Install dependency: watchdog
  • Keep handlers fast (offload heavy work)

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading