AW Dev Rethought

βœ‚οΈ Perfection is achieved not when there is nothing more to add, but when there is nothing left to take away - Antoine de Saint-ExupΓ©ry

🧩 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!