Monitor File System Events with Watchdog in Python

  • Share this:

Code introduction


This code defines a function based on the watchdog library to monitor file system events on a specified path, such as file creation, modification, and deletion. When a file system event occurs, it prints out the corresponding information.


Technology Stack : watchdog

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def random_watchdog_function(path):
    # Create a custom event handler
    class CustomHandler(FileSystemEventHandler):
        def on_any_event(self, event):
            if event.is_directory:
                return
            elif event.event_type == 'created':
                print(f'File {event.src_path} has been created')
            elif event.event_type == 'modified':
                print(f'File {event.src_path} has been modified')
            elif event.event_type == 'deleted':
                print(f'File {event.src_path} has been deleted')

    # Create an observer
    event_handler = CustomHandler()
    observer = Observer()
    
    # Schedule the observer
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    
    observer.join()                
              
Tags: