from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyEventHandler(FileSystemEventHandler): def on_created(self, event): print(f"New file created: {event.src_path}") def on_deleted(self, event): print(f"File deleted: {event.src_path}") handler = MyEventHandler() observer = Observer() observer.schedule(handler, path='/path/to/directory', recursive=False) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()
import os import shutil import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MyEventHandler(FileSystemEventHandler): def on_created(self, event): print(f"New file created: {event.src_path}") backup_dir = '/path/to/backup/folder' shutil.copy2(event.src_path, backup_dir) def on_modified(self, event): print(f"File modified: {event.src_path}") backup_dir = '/path/to/backup/folder' shutil.copy2(event.src_path, backup_dir) handler = MyEventHandler() observer = Observer() observer.schedule(handler, path='/path/to/directory1', recursive=True) observer.schedule(handler, path='/path/to/directory2', recursive=True) observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() observer.join()Both examples demonstrate how to use the Observer class from the Python Watchdog package. The first example prints a message when files are created or deleted, and the second example moves newly created or modified files to a backup directory.