Automation & scripting
CLI tools, scheduled jobs, filesystem tasks, and glue scripts that save time.
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 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…
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 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…
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 Build a CLI with argparse in Python
Create a beginner-friendly command-line tool in Python that processes multiple filenames with optional flags for verbose output and uppercase conversion.
import argparse
def main():
parser = argparse.ArgumentParser(
description="A simple CLI to process files with optional verbose mode."
)
parser.add_argument("filenames", nargs="+", help="Files to process")
parser.add_argument("-v", "--verbose", action="store_true", help="Print extra details")
…
How to Build a Simple argparse CLI in Python
Create a beginner-friendly command-line tool with argparse that reads a file, optionally uppercases its lines, and prints a configurable number of lines.
import argparse
def main():
parser = argparse.ArgumentParser(
description="Automate file processing with a simple CLI tool."
)
parser.add_argument("filename", help="Path to the input file")
parser.add_argument("--uppercase", action="store_true", help="Convert text to uppercase")
parser.add…
How to Build an argparse CLI That Filters File Lines by Keyword in Python
This Python script is a command-line tool built with argparse that reads a text file and prints only the lines that contain (or don't contain) a given keyword.
import argparse
import sys
def main():
parser = argparse.ArgumentParser(description="Filter lines from a file by keyword.")
parser.add_argument("input", type=str, help="File to read")
parser.add_argument("keyword", type=str, help="Keyword to filter lines")
parser.add_argument("--contains", action="sto…
How to Build an argparse Command-Line Tool in Python
Create a simple file-info CLI with argparse that counts lines and prints file size, with optional verbose and output flags.
import argparse
import os
from pathlib import Path
def process_file(filepath, verbose=False):
"""Read a file and report its size and line count."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not found: {filepath}")
content = path.read_text()
lines = conten…
How to Bump Version in pyproject.toml Using Regex in Python
Updates the version field in a pyproject.toml file using a regex substitution with the Python standard library.
import re
from pathlib import Path
def bump_version(pyproject_path: str, new_version: str) -> None:
"""Update version in pyproject.toml using regex."""
path = Path(pyproject_path)
content = path.read_text()
# Match version = "x.y.z" (simple or PEP 440 with pre-release)
pattern = r'^version\s*=\s*…
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 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.
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
"…
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 Create a Password Protected Zip Archive in Python
Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.
import zipfile
import tempfile
import os
def create_password_protected_zip(zip_path, password: str, files: dict):
"""
Create a zip archive with password protection (mock encryption).
Args:
zip_path: Path where the zip file will be created
password: Password for the archive
files:…
How to Decrypt a GPG File with a Passphrase in Python
Decrypt a GPG-encrypted file using a passphrase via the gpg CLI wrapped in a reusable Python function.
import subprocess
import tempfile
from pathlib import Path
def decrypt_gpg_file(input_file: str, passphrase: str) -> str:
"""Decrypt a GPG file using a passphrase and return the plaintext."""
result = subprocess.run(
["gpg", "--batch", "--yes", "--passphrase", passphrase, "--decrypt", input_file],
…
How to Download a List of URLs to a Directory in Python
This script downloads a list of URLs into a specified directory, creating the folder if needed and keeping original filenames.
import urllib.request
from pathlib import Path
def download_urls(url_list, directory):
"""Download each URL in url_list into directory, keeping original filenames."""
save_dir = Path(directory)
save_dir.mkdir(parents=True, exist_ok=True)
for url in url_list:
filename = url.rstrip('/').spl…
How to Generate a QR Code in Python
Generate a QR code image from a URL string using the qrcode library and save it as a PNG file.
import qrcode
# Data to encode
data = "https://www.example.com"
# Create QR code instance
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
# Add data to QR code
qr.add_data(data)
qr.make(fit=True)
# Create an image from the QR code
img = qr.…
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.