Python File Change Monitor Using Watchdog Library

  • Share this:

Code introduction


This code defines a function named watch_directory that monitors file changes in a specified directory, including creation, modification, and deletion. It uses the Observer and FileSystemEventHandler classes from the watchdog library.


Technology Stack : The code uses the watchdog library, including the Observer and FileSystemEventHandler classes.

Code Type : The type of code

Code Difficulty : Advanced


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

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

class MyHandler(FileSystemEventHandler):
    def on_any_event(self, event):
        if event.is_directory:
            return None

        elif event.event_type == 'created':
            self.on_created(event)

        elif event.event_type == 'modified':
            self.on_modified(event)

        elif event.event_type == 'deleted':
            self.on_deleted(event)

    def on_created(self, event):
        print(f"File {event.src_path} has been created")

    def on_modified(self, event):
        print(f"File {event.src_path} has been modified")

    def on_deleted(self, event):
        print(f"File {event.src_path} has been deleted")