Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

115 matches
Strings & text easy

How to Detect Expired Domains Using Python

Parse a list of domain registration data and compare expiry dates to today to find expired domains.

datetime date-parsing domain-check
Python
import datetime

# List of test domains with fake registration and expiry dates
# Format: (domain, registration_date, expiry_date)
test_domains = [
    ('example.com', '2020-01-15', '2024-01-15'),  # Expired
    ('google.com', '1997-09-15', '2026-09-15'),   # Still active
    ('test-site.org', '2019-06-01', '2023-06-0…
51 0 Open
Files & data easy

Build a Python Script That Detects and Deletes Empty Files Across Folders

A Python script that recursively finds and removes all zero-byte files across nested directories, returning a list of deleted paths.

filesystem cleanup pathlib
Python
import os
from pathlib import Path

def find_and_delete_empty_files(root_dir: str) -> list:
    """Find and delete all empty files under root_dir. Returns list of deleted paths."""
    deleted = []
    for file_path in Path(root_dir).rglob('*'):
        if file_path.is_file() and file_path.stat().st_size == 0:
       …
57 0 Open
Files & data easy

How to Archive Old Files by Age in Python

Move files older than a specified number of days from a source directory to an archive directory using Python's pathlib and shutil modules.

file-archiving pathlib shutil
Python
import os
import shutil
import time
from pathlib import Path

def archive_old_files(source_dir: str, archive_dir: str, days_old: int) -> None:
    cutoff_time = time.time() - (days_old * 86400)  # 86400 seconds in a day
    archive_path = Path(archive_dir)
    archive_path.mkdir(parents=True, exist_ok=True)

    for i…
48 0 Open
Files & data easy

How to Prune Empty Directories in Python with os.walk

Remove all empty subdirectories bottom-up using os.walk with topdown=False and os.rmdir, safely ignoring non-empty folders.

os.walk filesystem cleanup
Python
import os

def prune_empty_dirs(root):
    """Remove all empty subdirectories under root, bottom-up."""
    for dirpath, dirnames, filenames in os.walk(root, topdown=False):
        if dirpath == root:
            continue
        try:
            os.rmdir(dirpath)
            print(f"Removed: {dirpath}")
        exce…
14 0 Open
Files & data easy

How to Watch a Directory for New Files in Python

Poll a directory at regular intervals and detect newly added files, printing each one as it appears.

file watching polling os.listdir
Python
import time
import os
from pathlib import Path

WATCH_DIR = Path("watched_files")

def watch_for_new_files(directory: Path, sleep_time: float = 1.0, max_iterations: int = 10):
    """Poll a directory for new files and print when one appears."""
    directory.mkdir(exist_ok=True)
    existing = set(os.listdir(directory…
12 0 Open
AI & LLM integration patterns easy

How to Build an Agent Loop with Plan, Act, Observe in Python

Implements a simple plan-act-observe loop that an AI agent uses to iteratively complete a task in an environment while storing observations in memory.

agents loop llm
Python
class Agent:
    def __init__(self, name):
        self.name = name
        self.memory = {}

    def plan(self, task):
        return f"Plan for {task}: step 1, step 2, step 3"

    def act(self, plan, environment):
        return f"Executing {plan} in {environment}"

    def observe(self, action_result):
        sel…
17 0 Open
Automation & scripting easy

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.

logs regex counter
Python
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…
21 0 Open
Automation & scripting easy

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.

automation tweeting blog
Python
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",
    …
16 0 Open
Automation & scripting easy

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.

hardware inventory psutil
Python
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…
55 0 Open
Automation & scripting easy

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.

psutil automation monitoring
Python
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…
50 0 Open
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 a Command-Line Password Generator in Python

Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.

secrets password-generator automation
Python
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__":…
48 0 Open
Automation & scripting easy

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.

datetime countdown timers
Python
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…
46 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

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.

subprocess ping exit-code
Python
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,
        …
16 0 Open
Automation & scripting easy

Create ICS Calendar Invites in Python

This script generates a batch of calendar invites in the ICS format using the ics library.

ics calendar automation
Python
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…
11 0 Open
Automation & scripting easy

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.

password secrets security
Python
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…
37 0 Open
Automation & scripting easy

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.

csv logs report
Python
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_…
14 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 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.

web-scraping automation download
Python
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…
38 0 Open
Automation & scripting easy

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.

sqlite backup automation
Python
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")
 …
14 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 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.

argparse cli scripting
Python
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")
 …
11 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.