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 file changes in a specified directory, including file creation, modification, and deletion. It randomly selects an event type to output corresponding messages.
Technology Stack : watchdog
Code Type : Python Function
Code Difficulty : Intermediate
import random
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def random_file_event_handler(path, event_type):
if event_type == 'modified':
print(f"File {path} has been modified.")
elif event_type == 'created':
print(f"File {path} has been created.")
elif event_type == 'deleted':
print(f"File {path} has been deleted.")
def start_watching_directory(directory):
event_handler = FileSystemEventHandler()
event_handler.on_any_event = random_file_event_handler
observer = Observer()
observer.schedule(event_handler, directory, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()