AW Dev Rethought

Programs must be written for people to read, and only incidentally for machines to execute - Harold Abelson

🧩 Python Automation Recipes – 👀 File Change Detector


Description:

📌 Introduction

Files change quietly — configs get updated, data files are modified, logs rotate. Manually tracking these changes is impractical, especially in automation-heavy workflows.

This automation recipe shows how to detect file changes automatically and trigger actions using Python. It’s a foundational pattern used in monitoring systems, build pipelines, and automation agents.


🔎 Explanation

  • The script watches a target file or folder.
  • It tracks the last modified timestamp of each file.
  • When a change is detected:
    • a message is logged
    • a custom action can be triggered (print, backup, notify, etc.)
  • The approach is simple, dependency-free, and easy to extend.

This pattern is commonly used for:

  • config reloads
  • file-based triggers
  • automation pipelines
  • development tooling

✅ Key Takeaways

  • 👀 Detect file changes automatically.
  • ⚡ Trigger actions the moment something changes.
  • 📦 Uses only Python’s standard library.

Code Snippet:

import time
from pathlib import Path
from datetime import datetime

# --- Step 1: Configuration ---

# Folder to monitor
WATCH_FOLDER = Path("")  # Change this

# Polling interval (seconds)
CHECK_INTERVAL = 5

# Store last known modification times
file_mod_times = {}

print(f"👀 Watching folder: {WATCH_FOLDER}\n")

# --- Step 2: Monitoring loop ---
while True:
    for file_path in WATCH_FOLDER.glob("*"):
        if file_path.is_file():

            last_modified = file_path.stat().st_mtime

            # First time seeing the file
            if file_path not in file_mod_times:
                file_mod_times[file_path] = last_modified
                continue

            # Detect modification
            if last_modified != file_mod_times[file_path]:
                file_mod_times[file_path] = last_modified
                timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

                print(f"[{timestamp}] File changed: {file_path.name}")

                # Trigger custom action here
                # e.g., backup file, reload config, send alert

    time.sleep(CHECK_INTERVAL)

Link copied!

Comments

Add Your Comment

Comment Added!