Reference library

Automation & scripting

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

18 matches
Automation & scripting easy

Batch Rename Hundreds of Files in Python

Rename all files with a given extension inside a folder using a sequential counter and a custom prefix.

automation files pathlib
Python
import os
from pathlib import Path

def batch_rename_files(directory: str, prefix: str, extension: str = ".txt") -> None:
    """Rename all files with given extension in directory to prefix_{counter}.ext."""
    path = Path(directory)
    if not path.is_dir():
        print(f"Directory '{directory}' does not exist.")
…
57 0 Open
Automation & scripting easy

Build an M3U Playlist from Folder MP3s in Python

Scans a folder for MP3 files and writes a valid M3U playlist with absolute file URIs.

m3u playlist pathlib
Python
from pathlib import Path
import sys


def build_playlist(folder: str, output: str = "playlist.m3u") -> str:
    folder_path = Path(folder)
    if not folder_path.is_dir():
        raise FileNotFoundError(f"Folder not found: {folder}")

    mp3_files = sorted(folder_path.glob("*.mp3"))
    if not mp3_files:
        pri…
17 0 Open
Automation & scripting easy

Bulk Rename Files in Python with Regex Replacement

Renames every file in a directory by applying a regex substitution to its filename using Python's stdlib re and pathlib.

automation regex pathlib
Python
import re
from pathlib import Path

def bulk_rename_regex(directory, pattern, replacement):
    path = Path(directory)
    renamed = []
    for file in path.iterdir():
        if file.is_file():
            new_name = re.sub(pattern, replacement, file.name)
            if new_name != file.name:
                new_pat…
17 0 Open
Automation & scripting easy

How to Auto Organize Downloads by File Extension in Python

A Python script that sorts files in a directory into subfolders based on their file extensions, creating folders automatically.

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

def organize_downloads(download_dir="~/Downloads"):
    """Move files in a directory into subfolders based on file extension."""
    download_path = Path(download_dir).expanduser()
    
    if not download_path.exists():
        print(f"Directory not found: {download_p…
13 0 Open
Automation & scripting easy

How to Batch Resize Images in Python with pathlib and Pillow

Batch resize all JPG images from a source folder and save to a destination folder using pathlib and Pillow.

pathlib pillow image-processing
Python
from pathlib import Path
from PIL import Image

def batch_resize_images(src_dir: str, dest_dir: str, size: tuple[int, int] = (800, 600)) -> None:
    src_path = Path(src_dir)
    dest_path = Path(dest_dir)
    dest_path.mkdir(parents=True, exist_ok=True)
    
    for img_path in src_path.glob("*.jpg"):
        if not …
12 0 Open
Automation & scripting easy

How to Clean Old Temp Files in Python

A Python script that scans a directory and deletes files older than a configurable age (default: one week), with safe error handling.

file-system cleanup pathlib
Python
import os
import time
from pathlib import Path

def clean_old_temp_files(directory=".", max_age_seconds=7 * 24 * 60 * 60):
    """
    Remove files in directory older than the specified age.
    
    Args:
        directory: Path to directory to clean
        max_age_seconds: Maximum age in seconds (default: 1 week)
 …
12 0 Open
Automation & scripting easy

How to Compress a Folder in Python While Preserving Directory Structure

A Python function that uses zipfile to recursively compress a folder, maintaining the original directory hierarchy inside the zip archive.

compression zipfile file-archiving
Python
import os
import zipfile
from pathlib import Path

def compress_folder(source_dir: str, output_zip: str):
    """
    Compress a folder into a zip file, preserving the directory structure.
    
    Args:
        source_dir: Path to the source directory to compress
        output_zip: Path for the output zip file
    "…
35 0 Open
Automation & scripting easy

How to Create a File Organizer That Sorts Files Automatically in Python

A Python script that scans a given folder, categorizes files by extension (Images, Documents, Audio, Video, Archives, Misc), and moves them into subfolders automatically.

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

FILE_CATEGORIES = {
    "Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp"],
    "Documents": [".pdf", ".docx", ".txt", ".csv", ".xlsx"],
    "Audio": [".mp3", ".wav", ".flac", ".aac"],
    "Video": [".mp4", ".mkv", ".avi", ".mov"],
    "Archives": [".zip", ".tar", ".g…
45 0 Open
Automation & scripting easy

How to Deploy a Static Site Build to an Nginx Directory in Python

Copy a static site build directory into an Nginx web root using Python's shutil and pathlib modules.

automation deployment shutil
Python
import shutil
import os
from pathlib import Path

SRC_DIR = Path("build")
DEST_DIR = Path("/var/www/html")

def deploy_site(src: Path, dest: Path) -> None:
    if not src.exists():
        raise FileNotFoundError(f"Build directory not found: {src}")

    dest.mkdir(parents=True, exist_ok=True)

    for item in src.ite…
16 0 Open
Automation & scripting easy

How to Hash Duplicate Photos and Delete Copies in Python

This script hashes image files in a directory using SHA-256 and deletes duplicate copies while keeping the first occurrence, ideal for cleaning up photo libraries.

hashlib deduplication file-automation
Python
from pathlib import Path
import hashlib

def file_hash(path, chunk_size=8192):
    hasher = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def delete_duplicate_photos(directory):
    directory …
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 Update a Hosts File to Block Distractions in Python

This script updates a local hosts file (or a demo file) by adding or updating entries to block distracting websites like Facebook and Twitter.

hosts-file automation blocking
Python
from pathlib import Path

def update_hosts(entries):
    """
    Add or update blocking entries in the hosts file.
    Uses a local demo file by default to avoid system changes.
    """
    hosts_path = Path("demo_hosts.txt")
    
    # Create demo file if it doesn't exist
    if not hosts_path.exists():
        hosts…
11 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 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…
40 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 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.