Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Write CSV file with csv DictWriter in Python
Write a list of dictionaries to a CSV file using Python's csv.DictWriter, including a header row.
import csv
from pathlib import Path
fieldnames = ["name", "city", "age"]
rows = [
{"name": "Alice", "city": "New York", "age": 30},
{"name": "Bob", "city": "Los Angeles", "age": 25},
{"name": "Charlie", "city": "Chicago", "age": 35},
]
path = Path("people.csv")
with path.open("w", newline="") as csvfile:…
How to Build a Data Helper Class in Python with OOP
Create a beginner-friendly Python class that loads CSV data, filters records by field, and counts entries using object-oriented programming.
class DataHelper:
"""A beginner-friendly OOP helper for handling simple datasets."""
def __init__(self, filename):
self.filename = filename
self.data = self._load_data()
def _load_data(self):
"""Load data from a CSV file into a list of dictionaries."""
import csv
…
How to Convert Data Types in Python with a Helper Class
This code defines a beginner-friendly OOP helper class for common data conversions like string to list, list to dict, JSON string, and CSV row, with an advanced subclass for numeric casting.
class DataConverter:
"""A beginner-friendly helper class for common data conversions."""
def __init__(self, data):
self.data = data
def to_list(self):
"""Convert string data (comma-separated) to a list."""
if isinstance(self.data, str):
return [item.strip() for…
Parse CSV Data with a Python Class
Encapsulate CSV file loading and column/row access methods in a reusable DataParser class for beginners.
class DataParser:
def __init__(self, file_path):
self.file_path = file_path
self.data = []
def load_data(self):
with open(self.file_path, 'r') as file:
for line in file:
row = line.strip().split(',')
self.data.append(row)
return self.…
How to Parse CSV Rows as Generator Dicts in Python
Reads a CSV file and yields each row as a dictionary one at a time using a generator, so the file is processed lazily.
import csv
from pathlib import Path
def csv_to_dicts(filepath):
with open(filepath, mode="r", newline="", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
yield row
if __name__ == "__main__":
sample_csv = Path("sample_data.csv")
sample_csv.write_text…
Automatically Generate Charts from CSV Files with One Command
Read a CSV file with headers, extract the first two numeric columns, and save a matplotlib line chart as a PNG image.
import csv
import sys
from pathlib import Path
import matplotlib.pyplot as plt
def generate_chart(csv_path: str) -> None:
"""Read a CSV file with headers and plot the first two numeric columns."""
data = []
with open(csv_path, 'r', newline='') as f:
reader = csv.reader(f)
headers = next(re…
Automatically Log CPU, RAM, and Disk Usage Every Minute in Python
This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.
import psutil
import time
import csv
from pathlib import Path
LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60
def log_system_usage():
"""Write CPU, RAM, and disk usage to CSV every minute."""
file_exists = LOG_FILE.exists()
with open(LOG_FILE, mode="a", newline="") as f:
writer = cs…
Build a Complete Web Scraper with Requests and BeautifulSoup in Python
Scrape multiple paginated pages from a website using Requests and BeautifulSoup, with retry logic, error handling, and CSV export.
import requests
from bs4 import BeautifulSoup
import csv
import time
from typing import List, Dict, Optional
class WebScraper:
def __init__(self, base_url: str, output_file: str = "scraped_data.csv"):
self.base_url = base_url
self.output_file = output_file
self.session = requests.Session()…
Generate a Monthly Report CSV from Log Files in Python
Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.
import csv
from collections import defaultdict
from datetime import datetime
def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
events_by_date = defaultdict(int)
revenue_by_date = defaultdict(float)
with open(log_file, 'r') as f:
for line in f:
date_…
How to Generate an Inventory CSV of Installed pip Packages in Python
This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.
import subprocess
import csv
def get_installed_packages():
"""Return a list of (name, version) tuples for installed pip packages."""
result = subprocess.run(
["pip", "list", "--format=freeze"],
capture_output=True,
text=True,
check=True
)
packages = []
for line in r…
How to Import Users from CSV into LDAP-like Dicts in Python
Reads a CSV of user records and converts each row into an LDAP-style dictionary with standard attributes using Python's csv module.
import csv
import io
from pathlib import Path
def mock_ldap_import(csv_path):
"""
Reads a CSV file with user data and returns a list of LDAP-like user dicts.
Adds standard LDAP attributes that would come from directory schema.
"""
with open(csv_path, newline="", encoding="utf-8") as csvfile:
…
Add a UUID Surrogate Key to Each Row in a CSV with Python
Generate a unique UUID string for every row in a CSV file using the standard-library uuid and csv modules.
import uuid
import csv
def add_surrogate_key(filename):
with open(filename, newline='') as f_in:
reader = csv.DictReader(f_in)
rows = list(reader)
for row in rows:
row['surrogate_key'] = str(uuid.uuid4())
with open(filename, 'w', newline='') as f_out:
writer = csv.DictWri…
ETL in Python: Extract CSV, Transform Dict, Load JSON
Build a simple ETL pipeline in Python that reads a CSV file, transforms each row (stripping whitespace and converting numeric fields), and writes the result to JSON.
import csv
import json
from pathlib import Path
def extract_csv(file_path):
"""Read CSV file and return list of row dictionaries."""
with Path(file_path).open('r', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
return list(reader)
def transform_dicts(rows):
"""Transform ro…
ETL in Python: Extract CSV, Transform Dicts, Load JSON
Build a simple ETL pipeline that reads a CSV, normalizes keys and converts price to float, then writes structured JSON.
import csv
import json
from pathlib import Path
def etl_csv_to_json(csv_path: str, json_path: str) -> None:
"""Extract CSV, transform rows to dicts, load to JSON."""
with open(csv_path, mode='r', newline='', encoding='utf-8') as f:
reader = csv.DictReader(f)
records = list(reader)
# Trans…
How to Build Data Processing Functions in Python
Create reusable helper functions to load, filter, transform, and aggregate CSV data in Python.
import csv
from pathlib import Path
def load_data(filepath):
"""Load CSV data into a list of dicts."""
with open(filepath, "r", newline="", encoding="utf-8") as f:
return list(csv.DictReader(f))
def filter_rows(rows, column, value):
"""Keep rows where column equals value."""
return [row for…
How to Convert Data Types in a Python Data Pipeline
Demonstrates a simple Python data pipeline that converts string values to proper types (bool, int, float, datetime) and outputs structured JSON.
import json
from datetime import datetime
def convert_value(value):
"""Convert string values to appropriate Python types."""
if value.lower() == "true":
return True
if value.lower() == "false":
return False
if value.isdigit():
return int(value)
try:
return float(val…
How to Process CSV Data in Python with a Data Helper
Build a beginner-friendly data helper in Python that loads a CSV file, filters rows by a condition, and summarizes numeric fields.
import csv
from pathlib import Path
DATA = [
{"name": "Alice", "score": 88, "passed": True},
{"name": "Bob", "score": 42, "passed": False},
{"name": "Carol", "score": 95, "passed": True},
]
def load_csv(file_path: Path) -> list[dict]:
with file_path.open(newline="", encoding="utf-8") as f:
r…
How to Validate Fact Table Grain Row Counts in Python
Validate fact table grain by checking dimension key references, unique grain combinations, duplicate rows, and dimension cardinality from a CSV file.
import csv
import hashlib
from pathlib import Path
def validate_fact_grain(fact_file: Path, expected_dim_keys: dict[str, set[str]]) -> dict:
"""
Validate fact table grain by checking each row's dimension keys exist
in expected dimension tables and row count consistency.
"""
dim_references = {}
…
Create a Data Helper Class for Beginners in Python
A simple Python class to read and write JSON and CSV files from a local directory, ideal for automating data workflows in cloud environments.
import json
from pathlib import Path
class DataHelper:
"""Simple helper for reading and writing common data files."""
def __init__(self, directory="data"):
self.directory = Path(directory)
self.directory.mkdir(exist_ok=True)
def save_json(self, filename, data):
filepath =…
How to plan reserved capacity from a CSV in Python
Read a CSV of workloads with csv.DictReader and compute a mock reserved capacity plan with headroom per service.
import csv
import io
def plan_reserved_capacity(workloads_csv: str) -> list[dict]:
"""Read a CSV of workloads and return a plan for reserved capacity per service."""
reader = csv.DictReader(io.StringIO(workloads_csv))
plan = []
for row in reader:
service = row["service"]
avg_load = fl…
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 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(…
Create a Data Helper Class in Python
A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.
import json
import csv
from pathlib import Path
class DataHelper:
def __init__(self, base_path="."):
self.base_path = Path(base_path)
self.base_path.mkdir(exist_ok=True)
def save_json(self, data, filename):
path = self.base_path / filename
with open(path, "w") as f:
…
How to Load CSV Training Data in Python Without Pandas
Load CSV training data using Python's standard library and mock it with io.StringIO for testing, returning headers and rows as dictionaries.
import csv
from pathlib import Path
def load_csv_training_data(file_path: str | Path) -> tuple[list[str], list[dict[str, str]]]:
"""Load CSV training data and return headers plus rows as dictionaries."""
with open(file_path, mode="r", newline="", encoding="utf-8") as csv_file:
reader = csv.DictReader…
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.