You can download this code by clicking the button below.
This code is now available for download.
This code defines a file monitoring function based on the watchdog library, randomly handles events such as creation, modification, and deletion, and continuously monitors a specified directory.
Technology Stack : watchdog library, file system event handling
Code Type : The type of code
Code Difficulty :
import random
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
def random_file_event_handler(path, event_type):
# This function handles file system events randomly selected from watchdog library
if event_type == 'created':
print(f"File {path} has been created.")
elif event_type == 'modified':
print(f"File {path} has been modified.")
elif event_type == 'deleted':
print(f"File {path} has been deleted.")
else:
print(f"Unknown event {event_type} for file {path}.")
def start_monitoring(directory):
# This function starts monitoring a directory for file system events
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:
# Run indefinitely until manually stopped
pass
except KeyboardInterrupt:
observer.stop()
observer.join()
# Code information