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…
Generate Holiday Calendars for Different Countries in Python
Generate a sorted list of public holidays for a given country and year using Python's calendar and datetime modules.
import calendar
from datetime import date, timedelta
def generate_holiday_calendar(country_code, year=2025):
holidays = []
if country_code == "US":
# New Year's Day
holidays.append(date(year, 1, 1))
# Independence Day
holidays.append(date(year, 7, 4))
# Thanksgivin…
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 Build a Python Tool That Finds Trending Open Source Projects Daily
A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.
import requests
import json
import datetime
def fetch_trending_projects(language: str = "", since: str = "daily"):
url = "https://api.github.com/search/repositories"
date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
query = f"created:>{date_limit} language:{language}" if langua…
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 Perform a DNS Lookup for A Records in Python
Resolve a hostname to IPv4 A records using Python's built-in socket.getaddrinfo and return a sorted list of addresses.
import socket
def get_a_records(hostname):
"""Fetch A records (IPv4 addresses) for a given hostname."""
try:
# getaddrinfo with family AF_INET restricts to IPv4 (A records)
infos = socket.getaddrinfo(hostname, None, socket.AF_INET)
# Each info tuple: (family, type, proto, canonname, so…
How to Sort Command-Line Arguments in Python
Build a beginner-friendly argparse CLI that sorts numbers or words passed as arguments, with an optional reverse flag.
import argparse
def main():
parser = argparse.ArgumentParser(description="Sort numbers or words from the command line.")
parser.add_argument("items", nargs="+", help="Items to sort (numbers or words)")
parser.add_argument("--reverse", "-r", action="store_true", help="Sort in descending order")
args =…
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.
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()
…
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.