Reference library

Python Code Samples

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

7 matches
Strings & text easy

How to Split Strings in Python (Beginner-Friendly)

Split Python strings by a delimiter into lists, plus a cleanup variant that strips whitespace and filters empty parts.

string split text parsing delimiter
Python
def split_text(text, delimiter=" "):
    """Split a string by a delimiter and return a list of parts."""
    return text.split(delimiter)


def split_text_with_cleanup(text, delimiter=" "):
    """Split a string, stripping whitespace and filtering empty parts."""
    parts = text.split(delimiter)
    cleaned = [part.s…
16 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:
       …
56 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
Comprehensions & generators easy

How to Close a Generator and Handle GeneratorExit in Python

This Python code demonstrates how to explicitly close a generator using the close() method and handle the GeneratorExit exception through a finally block to run cleanup logic.

generators generator-exit close
Python
def countdown(n):
    try:
        while n > 0:
            yield n
            n -= 1
    finally:
        print(f"Generator closed after countdown completed")


if __name__ == "__main__":
    gen = countdown(5)
    print(next(gen))
    print(next(gen))
    gen.close()
    print("Generator closed explicitly")
12 0 Open
Automation & scripting easy

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.

file-system cleanup pathlib
Python
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)
 …
12 0 Open
Automation & scripting easy

How to Filter Docker Containers for Pruning in Python

Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.

docker json datetime
Python
import json
from datetime import datetime, timedelta


def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
    containers = json.loads(json_output)
    cutoff = datetime.now() - timedelta(hours=older_than_hours)
    return [
        c for c in containers
        if datetime.fromisoformat(c["crea…
13 0 Open
Git + Python easy

How to Filter Git History to Remove Secret File Entries in Python

A pure-Python mock that filters a repository's history to drop any commit that touched a secret file, so you can plan a cleanup before rewriting Git history.

git secrets history
Python
from pathlib import Path
import json

def filter_history(history, secret_path):
    """Remove entries that touch the secret file."""
    return [entry for entry in history if secret_path not in entry["files"]]

if __name__ == "__main__":
    repo_history = [
        {"commit": "a1b2c3", "message": "Add app", "files": …
10 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.