Reference library

Automation & scripting

CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.

43 matches
Automation & scripting easy

How to Merge PDFs in Python (Mock pypdf Stub)

Merge PDF files by concatenating their raw byte content using a simple stubbed class that mimics the pypdf interface.

pdf merge mock
Python
import io
from hashlib import sha256


class PdfStub:
    def __init__(self, data: bytes, name: str):
        self.data = data
        self.name = name

    def get_content_bytes(self) -> bytes:
        return self.data


def merge_pdfs_mock(pdf_stubs) -> bytes:
    merged = io.BytesIO()
    for stub in pdf_stubs:
   …
14 0 Open
Automation & scripting easy

How to Quarantine Suspicious Files in Python

Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.

file-organization security automation
Python
import shutil
import os
from pathlib import Path

def quarantine_files(source_dir, quarantine_dir, suspicious_extensions):
    """
    Move files with suspicious extensions to a quarantine folder.
    Returns list of moved files.
    """
    source_path = Path(source_dir)
    quarantine_path = Path(quarantine_dir)
   …
11 0 Open
Automation & scripting easy

How to Recover Deleted .txt Files from a Backup in Python

A Python function that searches a backup directory recursively and copies all .txt files to a destination folder, printing each recovered file name and a total count.

backup recovery file-operations
Python
import os
import shutil
from pathlib import Path

def recover_deleted_txt_files(source_backup_dir: str, destination_dir: str) -> None:
    """Recover .txt files from backup directory."""
    backup_path = Path(source_backup_dir)
    dest_path = Path(destination_dir)
    dest_path.mkdir(parents=True, exist_ok=True)

  …
40 0 Open
Automation & scripting easy

How to Resize Hundreds of Images in Batch with Python

Resize every image in a folder to a target size using Pillow, creating a new subfolder for processed files.

image processing batch processing pillow
Python
import os
from PIL import Image

def resize_images_in_batch(directory, output_size=(800, 600)):
    if not os.path.exists(directory):
        print(f"Directory {directory} does not exist.")
        return
    output_dir = os.path.join(directory, "resized")
    os.makedirs(output_dir, exist_ok=True)
    for filename in…
41 0 Open
Automation & scripting easy

How to Save a VM Snapshot State to a JSON File in Python

Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.

json dataclass files
Python
import json
from dataclasses import dataclass, asdict
from pathlib import Path


@dataclass
class VMSnapshot:
    name: str
    memory_mb: int
    disk_gb: int
    state: str = "saved"

    def snapshot_to_file(self, path: Path) -> str:
        """Write snapshot state to a JSON file and return the filename."""
       …
13 0 Open
Automation & scripting medium

How to Scan Configuration Files for Security Issues in Python

Automatically scan configuration files for common security mistakes using regex rules in Python.

security config regex
Python
import re
import os
from pathlib import Path

SECURITY_RULES = [
    (r'^#\s*INSECURE_', 'Insecure comment starts with # INSECURE_'),
    (r'password\s*=\s*("|\\\')?[^"\\\'"\s]+("|\\\')?$', 'Hardcoded password'),
    (r'debug\s*=\s*True', 'Debug mode enabled'),
    (r'[Pp]ermit[Rr]ootLogin\s+yes', 'PermitRootLogin ena…
48 0 Open
Automation & scripting easy

How to Scan Files Against a Malware Hash List in Python

Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.

hashlib file-scanning security
Python
import hashlib
from pathlib import Path

# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"

KNOWN_MALWARE_HASHES = {
    "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}

def sha25…
14 0 Open
Automation & scripting medium

How to Sync Two Directories in Python (rsync-like)

Mirror a source directory into a destination by copying new or changed files and deleting extras, similar to rsync.

sync directory rsync
Python
import os
import shutil
import sys
from pathlib import Path

def sync_dirs(src: Path, dst: Path):
    """Mirror src into dst: copy new files, overwrite changed, delete extras."""
    dst.mkdir(parents=True, exist_ok=True)
    for dst_entry in dst.rglob('*'):
        rel = dst_entry.relative_to(dst)
        src_entry =…
14 0 Open
Automation & scripting easy

How to Tail and Colorize Error Lines in Python

Reads the last N lines of a log file and prints error lines in red using ANSI color codes.

logging terminal colorize
Python
import sys
import time
from pathlib import Path

def tail_colorize(filename: str, lines: int = 20) -> None:
    """Read last N lines of a file, printing errors in red."""
    path = Path(filename)
    if not path.exists():
        print(f"File '{filename}' not found.", file=sys.stderr)
        return

    # Read last …
15 0 Open
Automation & scripting medium

How to Track GitHub Stars, Forks, and Watchers in Python

Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.

github api automation
Python
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime

REPOS = [
    "psf/requests",
    "python/cpython",
    "pallets/flask",
]
DATA_DIR = Path("github_metrics")

def fetch_repo_stats(repo):
    url = f"https://api.github.com/repos/{repo}"
    resp = requests.get(ur…
39 0 Open
Automation & scripting easy

How to Watch a Folder and Convert New Images in Python

Watch a folder for new files and mock-convert images by copying and renaming them in an output directory.

folder-watching automation pathlib
Python
import time
import hashlib
from pathlib import Path
from datetime import datetime

def mock_convert_image(source: Path, dest_dir: Path) -> Path:
    """Mock image conversion: copy bytes and add .converted suffix."""
    dest = dest_dir / f"{source.stem}.converted{source.suffix}"
    dest.write_bytes(source.read_bytes(…
12 0 Open
Automation & scripting medium

How to apply Kubernetes YAML files from a folder in Python

Uses the Kubernetes Python client to apply all YAML manifests in a directory, with sorted processing and per-file error handling.

kubernetes yaml automation
Python
import os
import yaml
from kubernetes import client, config
from kubernetes.utils import create_from_yaml

def apply_yaml_folder(folder_path):
    """Apply all YAML files in a folder using the Kubernetes mock client."""
    # Load mock configuration
    config.load_kube_config()
    k8s_client = client.ApiClient()

  …
12 0 Open
Automation & scripting easy

How to automatically organize your Downloads folder by file type in Python

This script scans the Downloads folder and moves files into sub-folders based on their extensions (e.g., Images, Documents, Videos).

file organization automation os
Python
import os
import shutil
from pathlib import Path

def organize_downloads_folder(downloads_path=None):
    if downloads_path is None:
        downloads_path = str(Path.home() / "Downloads")
    
    if not os.path.exists(downloads_path):
        print(f"Path {downloads_path} does not exist.")
        return
    
    fi…
39 0 Open
Automation & scripting medium

How to check Python files for common coding mistakes

Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.

ast linting code-quality
Python
import ast
import os
import sys

def check_file(filepath):
    try:
        with open(filepath) as f:
            code = f.read()
        tree = ast.parse(code, filename=filepath)
    except SyntaxError as e:
        print(f"{filepath}: SyntaxError: {e.msg}")
        return
    
    issues = []
    for node in ast.wal…
42 0 Open
Automation & scripting easy

How to rename music files by ID3 tags in Python

Renames MP3 files in a folder using artist and title extracted from ID3 tags, with a mock fallback that parses filenames.

file-renaming id3-tags mp3
Python
import os
import re
from pathlib import Path

def sanitize_filename(name: str) -> str:
    return re.sub(r'[<>:"/\\|?*]', '_', name).strip()

def rename_mp3_from_id3(path: Path) -> None:
    for f in path.glob("*.mp3"):
        # Mock ID3 extraction: derive artist/title from filename
        stem = f.stem
        if "…
12 0 Open
Automation & scripting medium

Mount ISO Loop Device Mock Script in Python

Simulate ISO mounting with a loop device using a mock class — useful for testing scripts that depend on mount/unmount without actual system privileges.

iso loop-device mock
Python
import os
import tempfile
from dataclasses import dataclass
from pathlib import Path

@dataclass
class LoopDevice:
    path: str
    iso_path: str
    mounted: bool = False

    def mount(self, mount_point: str):
        if self.mounted:
            raise RuntimeError(f"Loop device {self.path} already mounted")
      …
14 0 Open
Automation & scripting medium

Python: Archive Old Logs by Compressing Gzip by Age

A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.

gzip log-rotation automation
Python
import gzip
import os
import shutil
from pathlib import Path


def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
    """Compress log files older than max_age_days into .gz archives.
    
    Returns a list of compressed file paths.
    """
    cutoff = time.time() - max_age_days * 86400
    compressed = …
14 0 Open
Automation & scripting easy

Rename Files in Folder with Numeric Prefix in Python

Renames all files in a folder by adding a sequential numeric prefix (e.g., 01_, 02_) to each filename using pathlib.

file-renaming pathlib automation
Python
from pathlib import Path

def rename_with_numeric_prefix(folder_path):
    folder = Path(folder_path)
    for index, file_path in enumerate(folder.iterdir(), start=1):
        if file_path.is_file():
            new_name = f"{index:02d}_{file_path.name}"
            new_path = file_path.with_name(new_name)
           …
13 0 Open
Automation & scripting easy

Rotate API keys in Python by updating an .env template

Replace an old API key with a new one inside an .env template file, with a guard for missing keys.

api-keys env-files automation
Python
import json
from pathlib import Path

def rotate_api_keys(env_template_path: Path, old_key: str, new_key: str) -> None:
    """Replace an old API key with a new one in an .env template file."""
    content = env_template_path.read_text()
    if old_key not in content:
        print(f"Error: '{old_key}' not found in {e…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Automation & scripting — Python code examples

What you will find here

This page collects automation & scripting snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.