Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
How to Convert CSV Column Types While Reading in Python
Read a CSV file and automatically convert column values to int, float, str, or bool based on type suffixes in the header names.
import csv
from pathlib import Path
from typing import Any
def read_csv_with_types(filepath: str) -> list[dict[str, Any]]:
"""Read CSV and convert column types based on header suffixes."""
converters = {
"int": int,
"float": float,
"str": str,
"bool": lambda v: v.strip().lower(…
How to Parse Path Components with pathlib Path in Python
Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.
from pathlib import Path
if __name__ == "__main__":
p = Path("data/reports/2024/final.txt")
print(f"Path: {p}")
print(f"Parent: {p.parent}")
print(f"Name: {p.name}")
print(f"Stem: {p.stem}")
print(f"Suffix: {p.suffix}")
print(f"Parts: {p.parts}")
print(f"Anchor: {p.anchor}")
print(…
How to Generate Git LFS Extension Patterns in Python
This script builds mock Git LFS file patterns for common geospatial extensions and filters them based on compression suffixes.
import itertools
import re
LFS_EXTENSIONS = {".csv", ".geojson", ".tif", ".shp", ".gpkg"}
def build_mock_lfs_pattern(base_name="data_usgs_lidar"):
patterns = []
for ext in sorted(LFS_EXTENSIONS):
for variant in (("", ".lz4"), (".compressed",), (".b", ".a"), ("_v1", ".zip")):
full_pattern …
How to Generate Experiment Tracking Run IDs in Python
Generate unique experiment run IDs with timestamps and random suffixes for tracking ML pipeline executions.
import random
import string
import time
def generate_run_id(prefix="exp"):
timestamp = time.strftime("%Y%m%d_%H%M%S")
suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
return f"{prefix}_{timestamp}_{suffix}"
if __name__ == "__main__":
# Simulate tracking three experiment r…
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
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- 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.