The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Create a program to monitor local files

Here’s a simple Python program that monitors local files or directories for changes like creation, modification, and deletion. It uses the watchdog library, which is a popular and easy-to-use tool for file system monitoring.

python
import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class MonitorHandler(FileSystemEventHandler): def on_created(self, event): print(f"Created: {event.src_path}") def on_modified(self, event): print(f"Modified: {event.src_path}") def on_deleted(self, event): print(f"Deleted: {event.src_path}") def on_moved(self, event): print(f"Moved: from {event.src_path} to {event.dest_path}") def monitor_path(path_to_monitor): event_handler = MonitorHandler() observer = Observer() observer.schedule(event_handler, path=path_to_monitor, recursive=True) observer.start() print(f"Monitoring started on: {path_to_monitor}") try: while True: time.sleep(1) except KeyboardInterrupt: observer.stop() print("Monitoring stopped.") observer.join() if __name__ == "__main__": path = "./" # Change this to the folder you want to monitor monitor_path(path)

How to use:

  1. Install watchdog if you haven’t already:

    nginx
    pip install watchdog
  2. Change the path variable in the script to the directory you want to monitor.

  3. Run the script. It will print changes happening in the monitored folder and its subfolders.

This program continuously runs until you stop it (Ctrl+C), and reports on file creation, modification, deletion, and moving events.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About