The user wants a Python script to monitor file changes and trigger events.
This is a common task, and Python has several libraries for it. The most robust and cross-platform one is watchdog.
1. Understand the Goal:
Input: A directory path to watch.
Mechanism: Detect file system events (created, modified, deleted, moved).
Output: Trigger specific actions (print statements, function calls) when these events occur.
2. Choose the Right Tool:
Option A: os.listdir / os.stat polling. (Bad idea. High CPU usage, high latency, complex to implement diff logic).
Option B: Native OS APIs (inotify on Linux, ReadDirectoryChangesW on Windows, FSEvents on Mac).
Option C: A wrapper library. -> watchdog is the standard choice. It handles the OS-specific details and provides a clean API.
3. Design the Script using watchdog:
Install: Need to mention pip install watchdog.
Import:watchdog.observers, watchdog.events.
Event Handler Class: Create a class inheriting from FileSystemEventHandler.
Need methods for on_modified, on_created, on_deleted, on_moved.
Observer Setup:
Instantiate Observer().
Schedule the event handler for a specific path.
Start the observer loop.
Main Loop:
Keep the script running (usually observer.join() inside a try/except block for KeyboardInterrupt).
4. Draft the Code (Mental or Scratchpad):
python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f"File modified: {event.src_path}")
def on_created(self, event):
print(f"File created: {event.src_path}")
if __name__ == "__main__":
path = "."
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
5. Refine and Enhance:
The basic draft is good, but maybe too simple?
Filtering: Often people want to watch specific file types (e.g., .txt or .log). I should add a note or a small check for that.
Logging: It's better to use the logging module for professional scripts, but print is fine for a simple example. Let's stick to print for clarity but mention logging.
Structure: Organize the code cleanly with comments.
6. Create the Final Output:
Prerequisites: Explain how to install the library.
The Script: Provide the complete, runnable code.
Explanation: Break down how it works (Observer, Handler, Main Loop).
Customization: Give examples of how to extend it (e.g., filtering file extensions).
7. Self-Correction/Review during drafting:
Issue:watchdog sometimes triggers multiple events for a single modification (depending on the editor/OS).
Solution: I won't implement a complex debounce mechanism right now as it complicates the "basic" script, but I will mention that on_modified can be noisy.
Issue: Hidden files (like .DS_Store).
Solution: I'll keep the handler generic but mention in the customization section that logic can be added to ignore patterns.
This thought process moves from understanding the requirement to selecting the best tool, drafting the logic, refining the implementation details, and structuring the explanation for the user.
Here is a complete, robust Python script to monitor file changes.
The standard and most efficient way to do this in Python is using the watchdog library. It relies on OS-specific events (like inotify on Linux or FSEvents on macOS) rather than inefficient polling loops.
1. Prerequisites
You need to install the watchdog library:
bash
pip install watchdog
2. The Python Script
Save this code as monitor.py.
python
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
# Configure logging to show messages in the console
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
class ChangeHandler(FileSystemEventHandler):
"""
Custom event handler to react to file system changes.
"""
def on_modified(self, event):
if event.is_directory:
return
logging.info(f"File modified: {event.src_path}")
# Trigger your custom event here
# e.g., process_file(event.src_path)
def on_created(self, event):
if event.is_directory:
return
logging.info(f"File created: {event.src_path}")
# Trigger your custom event here
def on_deleted(self, event):
if event.is_directory:
return
logging.info(f"File deleted: {event.src_path}")
def on_moved(self, event):
if event.is_directory:
return
logging.info(f"File moved/renamed: from {event.src_path} to {event.dest_path}")
if __name__ == "__main__":
# Set the path to watch (defaults to current directory if no arg provided)
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = ChangeHandler()
observer = Observer()
# Schedule the observer to watch the path recursively
observer.schedule(event_handler, path, recursive=True)
print(f"🔍 Now watching directory: {path}")
print("Press Ctrl+C to stop.")
observer.start()
try:
# Keep the script running in a loop
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nStopping observer...")
observer.stop()
observer.join()
3. How to Run It
Open your terminal.
Run the script on a specific folder:
bash
python monitor.py /path/to/your/folder
Or run it on the current directory:
bash
python monitor.py
Create, modify, or delete files in that folder. You will see output like this:
The script above simply logs changes. To make it "trigger" an action, look at the methods inside the ChangeHandler class.
For example, if you want to automatically compress any new file added to the folder:
python
import zipfile
import os
class ChangeHandler(FileSystemEventHandler):
def on_created(self, event):
if event.is_directory:
return
filepath = event.src_path
# Example: Zip every new file created
print(f"New file detected: {filepath}. Zipping...")
try:
with zipfile.ZipFile(filepath + '.zip', 'w') as zipf:
zipf.write(filepath, os.path.basename(filepath))
print("Zipping complete.")
except Exception as e:
print(f"Error processing file: {e}")
A Note on Editors (VS Code, PyCharm)
Some text editors do not "modify" files directly. Instead, they save changes to a temporary file, delete the original, and rename the temp file to the original name.
If you notice on_modified isn't triggering when you save a text file, check if on_moved is triggering instead.
watchdog usually handles this gracefully, but it is a common point of confusion.