File Watcher

Monitor file system changes and trigger callbacks on events

python (3.9) 2025-11-12 filesystem monitoring events watch

Description

A file system watcher that monitors directories and files for changes. Triggers callbacks on create, modify, and delete events.

Features

  • Directory and file monitoring
  • Event filtering
  • Debounced callbacks
  • Recursive watching

Code

RAW
from watchdog.observers import Observerfrom watchdog.events import FileSystemEventHandlerfrom typing import Callable, Optionalfrom pathlib import Pathclass FileWatcher:    def __init__(self, path: str, callback: Callable, recursive: bool = true):        self.path = Path(path)        self.callback = callback        self.recursive = recursive        self.observer = Observer()        self.handler = FileChangeHandler(callback)        def start(self):        """Start watching for file changes."""        self.observer.schedule(self.handler, str(self.path), recursive=self.recursive)        self.observer.start()        def stop(self):        """Stop watching for file changes."""        self.observer.stop()        self.observer.join()        def __enter__(self):        self.start()        return self        def __exit__(self, exc_type, exc_val, exc_tb):        self.stop()class FileChangeHandler(FileSystemEventHandler):    def __init__(self, callback: Callable):        self.callback = callback        def on_created(self, event):        if not event.is_directory:            self.callback('created', event.src_path)        def on_modified(self, event):        if not event.is_directory:            self.callback('modified', event.src_path)        def on_deleted(self, event):        if not event.is_directory:            self.callback('deleted', event.src_path)
RAW
from file_watcher import FileWatcherdef on_change(event_type, file_path):    print(f'File {event_type}: {file_path}')watcher = FileWatcher('./', on_change, recursive=true)with watcher:    print('Watching for changes...')    import time    time.sleep(60)

Comments

No comments yet. Be the first to comment!