The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Make a file watcher that reacts to changes

Here’s a basic file watcher written in Python using the watchdog library. This script monitors a specified directory for file changes (creation, modification, deletion) and reacts by printing an event message. You can expand this to perform more complex actions as needed.

Prerequisites

Install watchdog if you haven’t already:

bash
pip install watchdog

Python Code

python
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class ChangeHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory: print(f"Modified file: {event.src_path}") def on_created(self, event): if not event.is_directory: print(f"Created file: {event.src_path}") def on_deleted(self, event): if not event.is_directory: print(f"Deleted file: {event.src_path}") def start_watching(path='.'): event_handler = ChangeHandler() observer = Observer() observer.schedule(event_handler, path=path, recursive=True) observer.start() print(f"Watching for changes in: {path}") try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join() if __name__ == "__main__": # Set the directory you want to monitor directory_to_watch = "./" # Change this as needed start_watching(directory_to_watch)

Key Features

  • Monitors all files in the given directory and subdirectories.

  • Detects and logs when files are created, modified, or deleted.

  • Easy to customize for specific file types or actions.

Let me know if you need a version in another language like Node.js, Go, or Bash.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About