import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # define a class to handle file system events class FileHandler(FileSystemEventHandler): def on_any_event(self, event): print(f"File system event detected: {event}") # define the observer object observer = Observer() # set the observer schedule to run every 5 seconds observer.schedule(FileHandler(), path='.', recursive=True) observer.start() # run the observer infinitely try: while True: time.sleep(5) except KeyboardInterrupt: observer.stop() observer.join()
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # define a class to handle file system events class FileHandler(FileSystemEventHandler): def on_modified(self, event): if event.is_directory: return None print(f"A file was modified: {event.src_path}") # define the observer object observer = Observer() # set the observer schedule to run every 10 seconds observer.schedule(FileHandler(), path='/path/to/file', recursive=False) observer.start() # run the observer infinitely try: while True: time.sleep(10) except KeyboardInterrupt: observer.stop() observer.join()The package library used in both examples is watchdog.