0
0
PythonHow-ToBeginner · 4 min read

How to Watch File Changes in Python Easily

To watch file changes in Python, use the watchdog library which monitors file system events like creation, modification, and deletion. You set up an Observer to watch a directory and define an EventHandler to respond to changes.
📐

Syntax

The basic syntax to watch file changes involves creating an Observer and an EventHandler. The Observer watches a directory path, and the EventHandler defines what to do when a file event happens.

  • Observer(): Watches for file system events.
  • EventHandler: Handles events like file created, modified, or deleted.
  • schedule(event_handler, path, recursive): Tells the observer which path to watch and whether to watch subfolders.
  • start(): Starts watching.
  • stop(): Stops watching.
python
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f"File modified: {event.src_path}")

observer = Observer()
handler = MyHandler()
observer.schedule(handler, path='.', recursive=True)
observer.start()

try:
    while True:
        pass  # Keep the script running
except KeyboardInterrupt:
    observer.stop()
observer.join()
💻

Example

This example watches the current folder and prints a message whenever a file is modified. It uses the watchdog library to detect changes and runs until you stop it with Ctrl+C.

python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Watcher(FileSystemEventHandler):
    def on_modified(self, event):
        if not event.is_directory:
            print(f"File changed: {event.src_path}")

observer = Observer()
handler = Watcher()
observer.schedule(handler, path='.', recursive=False)
observer.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
Output
File changed: ./example.txt File changed: ./notes.txt
⚠️

Common Pitfalls

Common mistakes when watching file changes include:

  • Not keeping the script running, so the observer stops immediately.
  • Forgetting to call observer.join() after stopping, which waits for the observer thread to finish.
  • Watching a directory without setting recursive=True if you want to watch subfolders.
  • Not handling events properly, for example, ignoring directory events when you only want files.
python
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class BadHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f"Changed: {event.src_path}")

observer = Observer()
handler = BadHandler()
observer.schedule(handler, path='.', recursive=False)
observer.start()
# Missing loop to keep script alive
observer.stop()
observer.join()
📊

Quick Reference

Here is a quick summary of key methods and classes for watching file changes with watchdog:

Method/ClassDescription
Observer()Creates a watcher for file system events
FileSystemEventHandlerBase class to handle file events
schedule(handler, path, recursive)Assigns a handler to watch a path, optionally recursive
start()Starts the observer thread
stop()Stops the observer
join()Waits for observer thread to finish
on_modified(event)Called when a file or folder is modified
on_created(event)Called when a file or folder is created
on_deleted(event)Called when a file or folder is deleted

Key Takeaways

Use the watchdog library's Observer and FileSystemEventHandler to watch file changes.
Keep your script running with a loop to allow continuous monitoring.
Set recursive=True to watch all subdirectories if needed.
Always stop and join the observer properly to clean up threads.
Filter events if you only want to respond to files or specific changes.