Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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.
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.")
…
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.
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…
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.
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…
Create a Simple HTTP File Server in Python
This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = os.getcwd()
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
def log_message(self, format, *args):
print(f"[{self.log…
Generate a Monthly Report CSV from Log Files in Python
Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.
import csv
from collections import defaultdict
from datetime import datetime
def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
events_by_date = defaultdict(int)
revenue_by_date = defaultdict(float)
with open(log_file, 'r') as f:
for line in f:
date_…
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.
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…
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.
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)
…
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.
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…
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.
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 …
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.
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:
…
How to Quarantine Suspicious Files in Python
Move files with suspicious extensions to a quarantine folder using pathlib and shutil for safe isolation.
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)
…
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.
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)
…
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.
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…
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.
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."""
…
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.
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…
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.
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 …
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.
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(…
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).
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…
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.
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 "…
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.
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)
…
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.
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…
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.