Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
Aggregate Log Errors Count by Hour in Python
Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.
import re
from collections import Counter
from datetime import datetime
def aggregate_errors_by_hour(log_lines):
pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
hourly_counts = Counter()
for line in log_lines:
match = pattern.match(line)
if match:
ho…
Automate Tweeting New Blog Posts in Python
A mock script that fetches new blog posts from a CMS and tweets them via a simulated Twitter API, outputting JSON results.
import json
import time
from datetime import datetime
def fetch_new_blog_posts():
"""Mock function to simulate fetching latest blog posts from a CMS."""
return [
{
"id": 1,
"title": "Getting Started with Python",
"url": "https://blog.example.com/python-start",
…
Automatically Generate Hardware Inventory Reports in Python
Generate a system hardware report including OS version, CPU cores, RAM, and disk usage using platform and psutil.
import platform
import psutil # requires: pip install psutil
from datetime import datetime
def generate_hardware_report():
report_lines = []
report_lines.append(f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report_lines.append(f"System: {platform.system()} {platform.release()} ({pl…
Automatically Log CPU, RAM, and Disk Usage Every Minute in Python
This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.
import psutil
import time
import csv
from pathlib import Path
LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60
def log_system_usage():
"""Write CPU, RAM, and disk usage to CSV every minute."""
file_exists = LOG_FILE.exists()
with open(LOG_FILE, mode="a", newline="") as f:
writer = cs…
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.")
…
Benchmark Disk Write Speed in Python with tempfile
Benchmark raw disk write performance by writing a temporary file in 1MB chunks and measuring throughput in MB/s.
import os
import tempfile
import time
def benchmark_write(size_mb=50):
size_bytes = size_mb * 1024 * 1024
chunk = b'x' * 1024 * 1024 # 1 MB chunk
with tempfile.NamedTemporaryFile(delete=True) as tmp:
start = time.perf_counter()
written = 0
while written < size_bytes:
…
Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
import secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":…
Build a Live Countdown Timer for Events in Python
A Python script that displays a real-time countdown to a target date and time, updating every second in the console.
import datetime
import time
def countdown(event_name, target_datetime):
"""Displays a live countdown to a target datetime."""
while True:
now = datetime.datetime.now()
remaining = target_datetime - now
if remaining.total_seconds() <= 0:
print(f"\n🚀 {event_name} is happening…
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…
Check Service Ping Status and Exit Code in Python
Ping a list of hosts, print OK/FAIL per host, and exit with a non-zero code when any host is unreachable.
import subprocess
import sys
SERVICES = [
"8.8.8.8",
"1.1.1.1",
"invalid-host",
]
def main():
failed = []
for host in SERVICES:
result = subprocess.run(
["ping", "-c", "1", "-W", "2", host],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
…
Convert Markdown to HTML in Python (Batch)
Convert every Markdown file in a directory to HTML with the Python markdown library, saving each result with an .html extension.
import markdown
from pathlib import Path
def convert_md_to_html(source_dir: str, dest_dir: str) -> list[str]:
src = Path(source_dir)
dst = Path(dest_dir)
dst.mkdir(parents=True, exist_ok=True)
converted_files = []
for md_file in src.glob("*.md"):
html_content = markdown.markdown(md_file.…
Create ICS Calendar Invites in Python
This script generates a batch of calendar invites in the ICS format using the ics library.
import ics
from datetime import datetime, timedelta
def create_invites(batch):
calendar = ics.Calendar()
for event_data in batch:
event = ics.Event()
event.name = event_data["name"]
event.begin = event_data["start"]
event.end = event_data["end"]
event.description = even…
Create Mock Watermarked Image Bytes in Python Without PIL
Builds a mock image-like byte stream with an embedded watermark using only stdlib modules, for testing pipelines without PIL.
from io import BytesIO
import zlib
import struct
def create_watermarked_bytes(width: int, height: int, watermark: bytes) -> bytes:
"""Create a mock image-like byte stream with a watermark (no PIL)."""
header = struct.pack("<2I", width, height)
payload = watermark * max(1, (width * height // max(1, len(wa…
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…
Fetch weather API mock and write dashboard HTML in Python
This script fetches a mock weather API response as a Python dict, builds a simple HTML dashboard, writes it to a file, and prints both the file path and JSON payload.
from datetime import datetime
import json
import os
def fetch_weather_mock(city: str) -> dict:
"""Return a mock weather payload for a given city."""
return {
"city": city,
"temperature_c": 21.5,
"condition": "Partly Cloudy",
"humidity": 58,
"wind_kph": 12.3,
"u…
Fill PDF Form Fields from a Mock Template in Python
Fills a PDF-style form template dictionary with user data, preserving template fields and formatting output as JSON.
import json
template = {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"date_of_birth": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"agree_to_terms": False
}
def fill_pdf_form(template: dict, data: dict) -> dict:
for key, value in data.items…
Generate Random Fake User Data for Testing in Python
This code generates a list of fake user dictionaries with random names, emails, ages, and timestamps using the Python standard library for testing purposes.
import json
import random
import string
from datetime import datetime, timedelta
def generate_user_data(num_users=1):
first_names = ["Alice", "Bob", "Charlie", "Diana", "Eve"]
last_names = ["Smith", "Johnson", "Brown", "Taylor", "Wilson"]
domains = ["example.com", "test.org", "demo.net"]
users = …
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
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 Automatically Download Every Favicon from a List of Websites in Python
Download each website's favicon.ico file by constructing its URL, making a GET request, and saving the binary content locally.
import requests
from urllib.parse import urlparse
import os
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.stackoverflow.com"
]
def download_favicon(url):
parsed = urlparse(url)
favicon_url = f"{parsed.scheme}://{parsed.netloc}/favicon.ico"
response = requests.g…
How to Backup an SQLite Database with a Timestamp in Python
Backs up an SQLite database file to a timestamped copy using the sqlite3 backup API.
import sqlite3
import shutil
from datetime import datetime
from pathlib import Path
def backup_database(db_path: str, backup_dir: str = "backups") -> Path:
db = Path(db_path)
backup_folder = Path(backup_dir)
backup_folder.mkdir(exist_ok=True)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
…
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.
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 …
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.