Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
Data Conversion Helper Functions in Python
A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.
from datetime import datetime
from pathlib import Path
import json
def to_json(data, indent=2):
"""Convert Python data to pretty-printed JSON string."""
return json.dumps(data, indent=indent, default=str)
def from_json(json_string):
"""Parse JSON string back into Python data."""
return json.loads(jso…
How to Load and Inspect CSV Data with a Dataclass Helper in Python
This code defines a DataHelper dataclass that reads a CSV file into a list of dictionaries and prints basic dataset information.
from pathlib import Path
from dataclasses import dataclass
from typing import Any
@dataclass
class DataHelper:
"""Simple helper for loading and inspecting CSV data."""
filepath: Path
def load_csv(self, *, delimiter: str = ",") -> list[dict[str, Any]]:
"""Read CSV into a list of dictionaries."""
…
How to Load and Inspect Data Files in Python
A beginner-friendly DataLoader dataclass that loads JSON or text files and provides methods to preview and inspect the data.
from dataclasses import dataclass, field
from pathlib import Path
import json
from typing import Any, Dict, List
@dataclass
class DataLoader:
"""Simple helper to load and inspect data files for beginners."""
path: Path
data: Any = field(init=False, default=None)
def __post_init__(self) -> None:
…
How to Load and Save CSV and JSON Files in Python
A beginner-friendly data helper that loads or saves CSV and JSON files using only the Python standard library, with automatic format detection from the file extension.
from pathlib import Path
import json
import csv
def load_data(file_path):
"""Load CSV or JSON data from disk based on file extension."""
path = Path(file_path)
if path.suffix == ".json":
with path.open() as f:
return json.load(f)
elif path.suffix == ".csv":
with path.open(…
How to Mock a pyenv Local Version File in Python
Read and write a mock .python-version file using the pathlib module and tempfile for isolated testing.
import json
import tempfile
from pathlib import Path
def read_pyenv_local(directory: Path) -> str:
"""Read the .python-version file in the given directory."""
version_file = directory / ".python-version"
if not version_file.exists():
return "no-version-file"
return version_file.read_text().st…
How to Parse and Extract Nested Data in Python
Load JSON files with Path and recursively extract values by key from nested Python structures using modern typing and standard library.
import json
from pathlib import Path
from typing import Any, Dict, List, Union
def load_data(filepath: Union[str, Path]) -> Union[Dict[str, Any], List[Any]]:
"""Load JSON data from a file with modern Path handling."""
path = Path(filepath)
if not path.exists():
raise FileNotFoundError(f"File not f…
How to Read the Python Path from VS Code settings.json in Python
This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.
import json
from pathlib import Path
from unittest.mock import patch
def read_vscode_python_path(settings_path: Path) -> str:
"""Extract python.defaultInterpreterPath from VS Code settings.json."""
with open(settings_path, "r") as f:
settings = json.load(f)
return settings.get("python", {}).get("d…
How to Save and Load JSON Files in Python
Create a simple data helper to save Python dictionaries as pretty-printed JSON files and load them back reliably using pathlib and the stdlib json module.
import json
from pathlib import Path
from typing import Any
def save_json(data: Any, filename: str) -> None:
"""Save data as pretty-printed JSON to the current directory."""
path = Path(filename)
with path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
def lo…
Browse by section
Each section groups closely related Python snippets.
Modern tooling — Python code examples
What you will find here
This page collects modern tooling snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
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.