2 min read

File System Monitor

This utility monitors a specific directory (and its subdirectories) for file system events such as file creation, deletion, modification, or moving. This is useful for tracking changes in a Downloads folder, a project directory, or a web server root.

Modules Used:

  • watchdog: A Python API library and shell utilities to monitor file system events.
  • time: To keep the script running.
  • logging: To log the events to a file or console.
  • argparse: To handle command-line arguments.

Prerequisites

This script needs to run continuously in the background to monitor changes. You can run it in a terminal window that you keep open, or use a tool like screen or tmux on Linux/macOS to keep it running after you disconnect.

Installation

pip install watchdog

The Code

Save this as fs_monitor.py.

import sys
import time
import logging
import argparse
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MonitorHandler(FileSystemEventHandler):
    """Logs all the events captured."""

    def on_moved(self, event):
        what = 'directory' if event.is_directory else 'file'
        logging.info(f"Moved {what}: from {event.src_path} to {event.dest_path}")

    def on_created(self, event):
        what = 'directory' if event.is_directory else 'file'
        logging.info(f"Created {what}: {event.src_path}")

    def on_deleted(self, event):
        what = 'directory' if event.is_directory else 'file'
        logging.info(f"Deleted {what}: {event.src_path}")

    def on_modified(self, event):
        what = 'directory' if event.is_directory else 'file'
        logging.info(f"Modified {what}: {event.src_path}")

def start_monitoring(path_to_watch):
    # Configure logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        handlers=[
            logging.FileHandler("file_changes.log"),
            logging.StreamHandler(sys.stdout)
        ]
    )

    event_handler = MonitorHandler()
    observer = Observer()
    observer.schedule(event_handler, path_to_watch, recursive=True)

    print(f"Monitoring started on: {path_to_watch}")
    print("Press Ctrl+C to stop.")

    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="File System Monitor")
    parser.add_argument("path", help="Directory path to monitor")

    args = parser.parse_args()

    start_monitoring(args.path)

Usage

# Monitor your Downloads folder (Windows example)
python fs_monitor.py "C:\Users\YourUser\Downloads"

# Monitor a project folder on Linux/macOS
python fs_monitor.py ~/projects/my-app

The script will log all file changes to the console and to a file named file_changes.log in the directory where the script is run.

programming/python/python