Reference library

Python Code Samples

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

106 matches
Errors & debugging easy

How to Mock a Failing Dependency to Test Error Paths in Python

Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.

testing mocking requests
Python
import requests

def fetch_user(user_id):
    url = f"https://api.example.com/users/{user_id}"
    response = requests.get(url, timeout=5)
    response.raise_for_status()
    return response.json()

def get_user_name(user_id, http_client):
    try:
        user_data = http_client(user_id)
        return user_data["nam…
16 0 Open
Errors & debugging easy

How to Use a Fallback Path with FileNotFoundError in Python

Read a primary file and fall back to a backup file when the first is missing, returning an empty string if both fail.

filenotfounderror exceptions fallback
Python
import pathlib

def read_config(path):
    primary = pathlib.Path(path)
    fallback = pathlib.Path("config_backup.json")
    try:
        with primary.open("r") as f:
            return f.read()
    except FileNotFoundError:
        try:
            with fallback.open("r") as f:
                return f.read()
      …
11 0 Open
Files & data easy

Append a Line to a Log File in Python

Append a line to a file using a context manager and Path.open().

file-io logging pathlib
Python
from pathlib import Path

def append_to_log(filepath, message):
    with Path(filepath).open("a") as log_file:
        log_file.write(f"{message}\n")

if __name__ == "__main__":
    log_path = "log.txt"
    append_to_log(log_path, "First entry")
    append_to_log(log_path, "Second entry")
    
    # Verify contents
  …
19 0 Open
Files & data easy

Build a File Index by Relative Path Hash Map in Python

Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.

os.walk file-index defaultdict
Python
import os
from collections import defaultdict


def build_file_index(root_dir):
    index = defaultdict(list)

    for dirpath, dirnames, filenames in os.walk(root_dir):
        for filename in filenames:
            full_path = os.path.join(dirpath, filename)
            relative_path = os.path.relpath(full_path, roo…
19 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

Build a Simple ETL Pipeline in Python

A simple ETL pipeline that reads JSON Lines, transforms records with filtering and normalization, and writes the result to JSON.

etl json jsonl
Python
import json
from pathlib import Path


def read_input(file_path: Path) -> list[dict]:
    """Read JSON lines file into list of dicts."""
    with file_path.open("r", encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def transform(records: list[dict]) -> list[dict]:
    """Transf…
13 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

Compress and Extract ZIP Files Programmatically in Python

Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.

zip compression file-io
Python
import zipfile
from pathlib import Path
import tempfile
import os

def create_sample_zip(zip_path: str, files: dict) -> None:
    """Create a ZIP file containing the given files (name -> content mapping)."""
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
        for filename, content in files.ite…
99 0 Open
Files & data easy

Convert All Markdown Files in a Folder to HTML in Python

Batch convert every .md file in a folder to .html using the `markdown` library with the 'extra' extensions.

markdown html batch-conversion
Python
import os
import markdown
from pathlib import Path

def convert_md_folder_to_html(input_folder="markdown_files", output_folder="html_pages"):
    input_path = Path(input_folder)
    output_path = Path(output_folder)
    output_path.mkdir(exist_ok=True)
    
    for md_file in input_path.glob("*.md"):
        with open…
55 0 Open
Files & data easy

Convert File Data to a Dictionary in Python

This function scans a directory and converts each file's metadata (name, size, extension) into a structured dictionary for easy access.

file-metadata pathlib directory
Python
from pathlib import Path

def convert_files_data(directory: str) -> dict:
    data = {}
    base = Path(directory)
    if not base.exists():
        return data
    for file in base.iterdir():
        if file.is_file():
            data[file.name] = {
                "size": file.stat().st_size,
                "exten…
15 0 Open
Files & data easy

Count Files by Extension in Python

Count files in a directory grouped by file extension using Python's standard library.

files pathlib directory
Python
from pathlib import Path

def count_files_by_extension(directory: str) -> dict[str, int]:
    """Count files in a directory grouped by file extension."""
    data = {}
    for path in Path(directory).iterdir():
        if path.is_file():
            ext = path.suffix.lower() or "(no extension)"
            data[ext] =…
14 0 Open
Files & data easy

Extract a Single Member from a ZIP Archive in Python

Extract one specific file from a ZIP archive to an output directory using the standard zipfile and pathlib modules.

zipfile zip extraction
Python
import zipfile
from pathlib import Path

def extract_single_member(zip_path: str, member_name: str, output_dir: str = ".") -> Path:
    """Extract a single member from a zip archive to the output directory."""
    with zipfile.ZipFile(zip_path, "r") as archive:
        archive.extract(member_name, output_dir)
    retu…
19 0 Open
Files & data easy

File Data Helper Functions in Python

Read and write text and JSON files, and list files in a directory, using pathlib-based helper functions.

file-io pathlib json
Python
from pathlib import Path

def load_text_file(filepath):
    """Read a text file and return its contents as a string."""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"File not found: {filepath}")
    return path.read_text(encoding="utf-8")

def save_text_file(filepath, content):
…
14 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 Compare Directory Trees in Python

This code recursively scans two directory trees and reports files that exist in only one directory, as well as files present in both but with different content.

filesystem comparison pathlib
Python
from pathlib import Path

def compare_directories(path1, path2):
    dir1 = Path(path1)
    dir2 = Path(path2)

    if not dir1.is_dir() or not dir2.is_dir():
        raise ValueError("Both paths must be directories.")

    files1 = {p.relative_to(dir1) for p in dir1.rglob("*") if p.is_file()}
    files2 = {p.relative…
11 0 Open
Files & data easy

How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

hashlib sha256 file-hash
Python
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_fi…
16 0 Open
Files & data easy

How to Copy a File with shutil.copy2 in Python

Copy a file while preserving metadata like timestamps and permissions using Python's shutil.copy2 and pathlib.

shutil file-copy pathlib
Python
import shutil
from pathlib import Path

source = Path("sample.txt")
destination = Path("sample_copy.txt")

source.write_text("Hello, PythonSkillset!")

if __name__ == "__main__":
    shutil.copy2(source, destination)
    copied = destination.read_text()
    print(f"Copied content: {copied}")
    print(f"Source exists:…
11 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 Delete a File if it Exists in Python

Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.

pathlib file-deletion file-management
Python
from pathlib import Path

def delete_file_if_exists(file_path: str) -> bool:
    """Delete a file if it exists. Returns True if deleted, False if not found."""
    path = Path(file_path)
    if path.exists():
        path.unlink()
        print(f"Deleted: {path}")
        return True
    else:
        print(f"File not…
14 0 Open
Files & data easy

How to Filter Files by Extension and Size in Python

Use pathlib to list files in a directory, filter by extension or minimum size, and return matching names or (name, size) pairs.

pathlib filesystem filtering
Python
from pathlib import Path

def filter_files_by_extension(directory: str, extension: str) -> list:
    """Return a list of file names in directory with the given extension."""
    path = Path(directory)
    return [f.name for f in path.iterdir() if f.is_file() and f.suffix == extension]

def filter_files_by_size(directo…
13 0 Open
Files & data easy

How to Find Files by Extension in Python

This code walks a directory tree with pathlib, collects all file paths, and counts them by extension to summarize a project's contents.

pathlib file-system recursion
Python
from pathlib import Path

def get_project_files(base_path="."):
    """Return a sorted list of all file paths under base_path."""
    base = Path(base_path)
    files = [p for p in base.rglob("*") if p.is_file()]
    return sorted(files)

def count_by_extension(files):
    """Return a dict mapping extension (lowercase…
12 0 Open
Files & data easy

How to Group Files by Extension in Python

Group file names by their file extension using a dictionary and pathlib, producing a simple clear mapping for beginners.

pathlib grouping filesystem
Python
from pathlib import Path


def group_data_by_extension(files: list[Path]) -> dict[str, list[str]]:
    """Group file names by their extension."""
    grouped: dict[str, list[str]] = {}
    for file in files:
        ext = file.suffix.lower()
        grouped.setdefault(ext, []).append(file.name)
    return grouped


if…
14 0 Open
Files & data easy

How to Handle Missing Values in a CSV Numeric Column in Python

Clean missing entries in a CSV numeric column by filling them with the mean, median, a custom value, or dropping rows.

csv data-cleaning statistics
Python
import csv
from pathlib import Path
import statistics

def clean_csv_numeric(input_path: str, output_path: str, column: str, strategy: str = "mean") -> None:
    """
    Handles missing values in a numeric column of a CSV file.
    Strategies: 'mean', 'median', 'drop', or 'fill' with a specified value.
    """
    row…
12 0 Open
Files & data easy

How to List File Information in a Directory with Python

A helper that walks a directory and returns each file's name, size, and extension as a list of dictionaries.

pathlib filesystem file-metadata
Python
from pathlib import Path


def get_files_data(directory: str) -> list[dict]:
    """Return basic info about all files in a directory."""
    files = []
    for path in Path(directory).iterdir():
        if path.is_file():
            files.append({
                "name": path.name,
                "size": path.stat()…
12 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.