Monitoring Directory Modifications with Watchdog Library

  • Share this:

Code introduction


This code defines a function `watch_directory` that uses the `watchdog` library to monitor file modification events in a specified directory. When a file is modified, it calls the callback function passed in.


Technology Stack : watchdog, Observer, FileSystemEventHandler

Code Type : The type of code

Code Difficulty : Intermediate


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

def watch_directory(path, callback):
    event_handler = MyHandler(callback)
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

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

# Code Information