Reference library

Python Code Samples

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

10 matches
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

Compare Two Folder Structures and Find Differences in Python

Walks two directories using os.walk, builds sets of relative paths, and prints items that exist in only one folder.

filesystem os.walk comparison
Python
import os

def compare_folders(path1, path2):
    """
    Compare the file/folder structure of two directories and print differences.
    """
    def get_structure(root):
        structure = set()
        for dirpath, dirnames, filenames in os.walk(root):
            rel_path = os.path.relpath(dirpath, root)
         …
61 0 Open
Files & data easy

How to Create Nested Directories with pathlib mkdir parents in Python

Create nested directories with pathlib's Path.mkdir using parents=True and exist_ok=True to avoid errors when paths already exist.

pathlib mkdir directories
Python
from pathlib import Path

def create_nested_directories(base_path: str, dirs: list[str]) -> None:
    for directory in dirs:
        path = Path(base_path) / directory
        path.mkdir(parents=True, exist_ok=True)
        print(f"Created: {path}")

if __name__ == "__main__":
    root = "output"
    nested_dirs = ["2…
13 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 Split Files by Extension in Python

Group files in a folder by their file extension into a dictionary using pathlib.

pathlib filesystem grouping
Python
from pathlib import Path

def split_files_by_extension(folder_path):
    folder = Path(folder_path)
    files_by_ext = {}

    for file_path in folder.iterdir():
        if file_path.is_file():
            ext = file_path.suffix.lower() or "no_extension"
            files_by_ext.setdefault(ext, []).append(file_path.na…
12 0 Open
Git + Python easy

How to Get Git Status and Log in Python

A beginner-friendly helper that runs git status and git log from Python using subprocess, with safe handling for non-repo directories.

git subprocess cli
Python
import subprocess
from pathlib import Path


def git_status(path: str = ".") -> str:
    """Return the current git status as a string."""
    result = subprocess.run(
        ["git", "status", "--short"],
        cwd=path,
        capture_output=True,
        text=True
    )
    return result.stdout.strip() or "No cha…
14 0 Open
Git + Python easy

How to Mock Git Worktree Creation in Python

Create a mock Git worktree setup with parallel branch directories and state files for testing or simulation.

git worktree mock
Python
import os
import tempfile
from pathlib import Path

def create_mock_worktree(base_dir: Path, branches: list[str]) -> dict[str, Path]:
    """
    Mock Git worktree creation: creates parallel directories for each branch
    under the base directory, simulating independent worktrees.
    """
    worktrees = {}
    for b…
14 0 Open
Git + Python easy

How to Run Git Commands from Python with subprocess

This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.

git subprocess automation
Python
import subprocess


def git_status():
    """Return a short, human-readable git status."""
    try:
        output = subprocess.run(
            ["git", "status", "--short"],
            capture_output=True,
            text=True,
            check=True,
        ).stdout.strip()
        return output if output else "W…
13 0 Open
Testing & modern typing easy

How to Use the pytest tmp_path Fixture for Temporary Directories

Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.

pytest tmp_path fixtures
Python
import pytest


def test_write_and_read_file(tmp_path):
    # tmp_path is a pytest fixture that provides a temporary directory
    # unique to each test invocation
    data_file = tmp_path / "data.txt"
    data_file.write_text("hello world")
    assert data_file.read_text() == "hello world"


def test_multiple_tmp_pat…
15 0 Open
Production deployment patterns easy

How to Mock Multi-Stage Docker Builds in Python

Simulate a multi-stage Docker build in pure Python using classes and temp directories to understand how build stages copy artifacts into a final image.

docker multi-stage simulation
Python
# Simulate multi-stage Docker build with pure Python
from pathlib import Path
import tempfile
import shutil

class BuildContext:
    """Mimics a Docker build context with stages."""
    
    def __init__(self, name):
        self.name = name
        self.files = {}
    
    def add_file(self, dest, content):
        s…
14 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.