You can download this code by clicking the button below.
This code is now available for download.
This function uses the watchdog library to monitor filesystem events in a specified directory and prints out the event type and the file path where the event occurred to the console.
Technology Stack : watchdog
Code Type : The type of code
Code Difficulty : Intermediate
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def monitor_directory(path):
event_handler = DirectoryChangeHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
class DirectoryChangeHandler(FileSystemEventHandler):
def on_any_event(self, event):
print(f"Event type: {event.event_type} for {event.src_path}")