Skip to main content
TutorialsTools & Productivity

Python for Automation: Scripts Every Developer Should Have

Practical Python scripts for file management, data processing, API testing, and workflow automation that save hours every week.

Mbeah Essilfie

Mbeah Essilfie

June 19, 2026 at 06:03 AM

8 min read 2150 views
Python for Automation: Scripts Every Developer Should Have

Why Python for Automation?

Python's stdlib is rich enough for most automation tasks without any pip installs. It reads like pseudocode, making scripts easy to maintain months later.

1. Bulk File Renamer

import os
from pathlib import Path

def rename_files(directory: str, pattern: str, replacement: str):
    """Rename files matching a pattern."""
    path = Path(directory)
    renamed = 0

    for file in path.iterdir():
        if pattern in file.name:
            new_name = file.name.replace(pattern, replacement)
            file.rename(path / new_name)
            print(f"  {file.name} → {new_name}")
            renamed += 1

    print(f"\nRenamed {renamed} files.")

# Usage
rename_files("./images", "screenshot_", "blog-hero-")

2. CSV to JSON Converter

import csv
import json
from pathlib import Path

def csv_to_json(csv_path: str, output_path: str | None = None):
    """Convert CSV to JSON with automatic type inference."""
    records = []

    with open(csv_path, 'r') as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Try to convert numeric strings
            cleaned = {}
            for key, value in row.items():
                try:
                    cleaned[key] = int(value)
                except ValueError:
                    try:
                        cleaned[key] = float(value)
                    except ValueError:
                        cleaned[key] = value
            records.append(cleaned)

    out = output_path or csv_path.replace('.csv', '.json')
    Path(out).write_text(json.dumps(records, indent=2))
    print(f"Converted {len(records)} records → {out}")

csv_to_json("users.csv")

3. API Health Checker

import urllib.request
import json
import time

ENDPOINTS = [
    ("Production API", "https://api.example.com/health"),
    ("Staging API", "https://staging.api.example.com/health"),
    ("Documentation", "https://docs.example.com"),
]

def check_health():
    print(f"Health check at {time.strftime('%H:%M:%S')}\n")

    for name, url in ENDPOINTS:
        try:
            start = time.time()
            req = urllib.request.urlopen(url, timeout=5)
            elapsed = (time.time() - start) * 1000
            status = "✅" if req.status == 200 else "⚠️"
            print(f"  {status} {name}: {req.status} ({elapsed:.0f}ms)")
        except Exception as e:
            print(f"  ❌ {name}: {e}")

check_health()
Run this as a cron job or a pre-deploy check. Zero dependencies, works on any system with Python 3.

4. Git Stats Reporter

import subprocess
from collections import Counter
from datetime import datetime, timedelta

def git_stats(days: int = 30):
    """Show git contribution stats for the last N days."""
    since = (datetime.now() - timedelta(days=days)).strftime('%Y-%m-%d')

    result = subprocess.run(
        ['git', 'log', f'--since={since}', '--format=%an|||%s'],
        capture_output=True, text=True
    )

    authors = Counter()
    for line in result.stdout.strip().split('\n'):
        if '|||' in line:
            author, _ = line.split('|||', 1)
            authors[author.strip()] += 1

    print(f"Git contributions (last {days} days):\n")
    for author, count in authors.most_common():
        bar = "█" * min(count, 40)
        print(f"  {author:20s} {bar} {count}")

git_stats()

Automate the repetitive. Spend your brain cycles on problems that actually need a human.

DevOpsPython
Mbeah Essilfie

Written by Mbeah Essilfie

Fullstack Software Developer

Read next

The Complete Guide to Vue 3 Composables
12 min read

The Complete Guide to Vue 3 Composables

Understand the power of Vue 3's Composition API through practical, real-world composable patterns that you can use today.

Mbeah EssilfieMbeah Essilfie
990