Purfe

Learn, create and have fun with Python

How to monitor file system for changes with Python

Monitoring the filesystem for changes using Python and watchdog.
Watchdog cross platform library allows to detect changes made to files in the directory. There are options to specify patterns for files (think extensions) and set recursive flag for tracking changes in subdirectories.
Code snippet below can be abstracted into separate classes for easier re-use.

import time
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

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

def on_deleted(event):
    print(f"Someone deleted {event.src_path}!")

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

def on_moved(event):
    print(f"{event.src_path} moved to {event.dest_path}")

if __name__ == "__main__":
    # event handler
    patterns = "*" # file patterns we want to handle (all the files)
    ignore_patterns = "" # patterns that we don’t want to handle
    ignore_directories = False # True to be notified for regular files (not for directories)
    case_sensitive = True # made the patterns “case sensitive”
    my_event_handler = PatternMatchingEventHandler(patterns, 
                                                   ignore_patterns, 
                                                   ignore_directories, 
                                                   case_sensitive)

    # specify functions to be called when the corresponding event is raised
    my_event_handler.on_created = on_created
    my_event_handler.on_deleted = on_deleted
    my_event_handler.on_modified = on_modified
    my_event_handler.on_moved = on_moved

    # create observer to monitor filesystem for changes 
    # that will be handled by the event handler
    path = "." # current directory
    go_recursively = True # allow to catch all the events in the subdirs of current dir
    my_observer = Observer()
    # call the schedule method on Observer object
    my_observer.schedule(my_event_handler, path, recursive=go_recursively)
    # start the observer thread to get all the events.
    my_observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        my_observer.stop()
    my_observer.join()

Full tutorial by Davide Mastromatteo from thepythoncorner

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top