diff --git a/File_Change_Tracker_#1839/README.md b/File_Change_Tracker_#1839/README.md new file mode 100644 index 0000000..53d9fd8 --- /dev/null +++ b/File_Change_Tracker_#1839/README.md @@ -0,0 +1,98 @@ +# Folder Activity Monitor + +> A Python script that **monitors a folder in real-time** and logs whenever files are **added**, **deleted**, or **modified**. + +Ideal for developers, system admins, or anyone who wants to **track file system changes** automatically. + +--- + +## Features + +* Real-time monitoring of a folder +* Detects file **creation**, **deletion**, and **modification** +* Automatically logs all events with timestamps +* Saves logs to a file: `folder_activity.log` +* Works on **Windows**, **macOS**, and **Linux** +* Lightweight — only requires the `watchdog` library + +--- + +## Example Log Output + +When you add, remove, or modify files, a log entry is created automatically: + +``` +2025-10-31 10:42:11 - File created: /Users/Downloads/photo.jpg +2025-10-31 10:43:08 - File modified: /Users/Downloads/report.pdf +2025-10-31 10:44:22 - File deleted: /Users/Downloads/old_notes.txt +``` + +--- + +## How It Works + +1. Monitors a target folder using the [`watchdog`](https://pypi.org/project/watchdog/) library. +2. Detects three types of file system events: + + * **Created** + * **Deleted** + * **Modified** +3. Records each event with a timestamp in a log file named `folder_activity.log`. +4. Runs continuously until manually stopped with **Ctrl + C**. + +--- + +## Usage + +### 1. Clone or Download the Script + +Download or copy `folder_monitor.py` to your computer. + +### 2. Install the Required Library + +Use `pip` to install the `watchdog` library: + +```bash +pip install watchdog +``` + +### 3. Run the Script + +Open a terminal or command prompt and execute: + +```bash +python folder_monitor.py +``` + +You’ll be prompted to enter the folder you want to monitor. +If you press Enter without typing anything, it defaults to your **Downloads** folder. + +``` +=== Folder Activity Monitor === +Enter the folder path to monitor [/Users/deepak/Downloads]: +``` + +### 4. View the Log File + +All activity is logged in `folder_activity.log` in the same directory as the script. + +--- + +## Configuration + +| Option | Description | +| --------------------- | ------------------------------------------------------------------------- | +| **Folder to Monitor** | Any valid directory path. Defaults to the user's `Downloads` folder. | +| **Recursive** | Set `recursive=True` in the script to monitor subfolders. | +| **Log File** | Automatically created as `folder_activity.log` in the script’s directory. | + +--- + +## Notes + +* The script only tracks **file-level changes** by default (not folders). +* Press **Ctrl + C** to stop monitoring gracefully. +* Ensure you have read/write permissions for the folder you monitor. +* For performance, avoid using it on extremely large folders with thousands of files. + +--- diff --git a/File_Change_Tracker_#1839/folder_monitor.py b/File_Change_Tracker_#1839/folder_monitor.py new file mode 100644 index 0000000..478d80e --- /dev/null +++ b/File_Change_Tracker_#1839/folder_monitor.py @@ -0,0 +1,107 @@ +""" +This script monitors a specified folder in real-time and logs whenever +files are added, removed, or modified. It helps track file system changes +for auditing, debugging, or automation purposes. + +Example: + - A new file 'report.pdf' added → Logged as "File created" + - An existing file deleted → Logged as "File deleted" + - A file updated → Logged as "File modified" + +The script writes all events to a log file named 'folder_activity.log' +inside the same directory as this script. + +Dependencies: + - watchdog (install via pip) + pip install watchdog + +""" + +import time +import logging +from watchdog.observers import Observer +from watchdog.events import FileSystemEventHandler +from pathlib import Path + + +class FolderEventHandler(FileSystemEventHandler): + """ + Custom event handler that logs file system changes. + + Methods: + on_created(event): Triggered when a file/folder is created. + on_deleted(event): Triggered when a file/folder is deleted. + on_modified(event): Triggered when a file/folder is modified. + """ + + def on_created(self, event): + """Logs when a file or folder is created.""" + if not event.is_directory: + logging.info(f"File created: {event.src_path}") + + def on_deleted(self, event): + """Logs when a file or folder is deleted.""" + if not event.is_directory: + logging.info(f"File deleted: {event.src_path}") + + def on_modified(self, event): + """Logs when a file or folder is modified.""" + if not event.is_directory: + logging.info(f"File modified: {event.src_path}") + + +def monitor_folder(folder_path: str) -> None: + """ + Monitors the given folder and logs file events (create, delete, modify). + + Args: + folder_path (str): Path to the folder to be monitored. + + Returns: + None + """ + folder = Path(folder_path) + + # Validate folder path + if not folder.is_dir(): + print(f"Error: '{folder_path}' is not a valid directory.") + return + + # Set up logging configuration + logging.basicConfig( + filename="folder_activity.log", + level=logging.INFO, + format="%(asctime)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + + print(f"Monitoring started for folder: {folder.resolve()}") + print("Watching for file additions, deletions, and modifications...") + print("Press Ctrl + C to stop monitoring.\n") + + # Create an event handler and observer + event_handler = FolderEventHandler() + observer = Observer() + observer.schedule(event_handler, str(folder), recursive=False) + + # Start the observer + observer.start() + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + observer.stop() + print("\n Monitoring stopped by user.") + observer.join() + + +if __name__ == "__main__": + # Default folder to monitor (user's Downloads folder) + default_folder = Path.home() / "Downloads" + + print("=== Folder Activity Monitor ===") + folder_input = input(f"Enter the folder path to monitor [{default_folder}]: ").strip() + folder_to_monitor = folder_input if folder_input else str(default_folder) + + # Start monitoring + monitor_folder(folder_to_monitor)