Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Build CSV row from Python list with proper quoting
Converts a list of fields into a properly quoted CSV row string using the csv module.
import csv
import io
def build_csv_row(fields):
output = io.StringIO()
writer = csv.writer(output)
writer.writerow(fields)
return output.getvalue().rstrip("\r\n")
if __name__ == "__main__":
fields = ["Alice", "Smith", "123 Main St, Apt 4B", "alice@example.com"]
print(build_csv_row(fields))
How to Split a String by Comma in Python
Splits a comma-separated string into a list of trimmed items using Python's built-in split and a list comprehension.
def split_csv(line):
return [item.strip() for item in line.split(",")]
if __name__ == "__main__":
sample = "apple, banana, cherry, date"
result = split_csv(sample)
print(result)
print(f"Number of items: {len(result)}")
How to Parse a Comma String into a List of Integers in Python
Converts a comma-separated string into a list of integers, handling spaces and empty inputs.
def parse_csv_to_ints(text: str) -> list[int]:
"""Parse a comma-separated string into a list of integers."""
if not text.strip():
return []
return [int(part.strip()) for part in text.split(",") if part.strip()]
if __name__ == "__main__":
sample = "10, 20, 30, 40, 50"
result = parse_csv_to_…
Build a Personal Work Hours Tracker in Python
A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.
import csv
from pathlib import Path
from datetime import datetime, date
class WorkHoursTracker:
def __init__(self, file_path="work_hours.csv"):
self.file_path = Path(file_path)
if not self.file_path.exists():
with open(self.file_path, "w", newline="") as f:
writer = csv…
Convert CSV Files to JSON in Python
Convert a CSV file to a JSON file using Python's built-in csv and json modules.
import csv
import json
def csv_to_json(csv_filepath, json_filepath):
"""Convert a CSV file to a JSON file."""
with open(csv_filepath, mode='r', newline='') as csv_file:
reader = csv.DictReader(csv_file)
data = [row for row in reader]
with open(json_filepath, mode='w') as json_file:
…
Detect Outliers in CSV Data Using Z-Score in Python
Read a CSV file and detect outliers in a numeric column by computing z-scores, flagging those exceeding a given threshold — no machine learning required.
import csv
import statistics
from math import sqrt
def detect_outliers(csv_path, column_name, threshold=2.0):
"""Detect outliers in a numeric column using z-score method."""
values = []
with open(csv_path, 'r', newline='') as f:
reader = csv.DictReader(f)
if column_name not in reader.field…
Export List of Dicts to CSV in Python
Write a list of dictionaries (dataframe-like) to a CSV file with headers using the standard library csv module and verify by reading it back.
import csv
def export_to_csv(data, filename):
"""Export a list of dicts to a CSV file."""
if not data:
print("No data to export")
return
# Get column names from the keys of the first dict
fieldnames = list(data[0].keys())
with open(filename, 'w', newline='', encoding='utf…
Export SQLite Query Results to CSV in Python
Connects to a SQLite database, runs a query, and writes the result rows and column headers to a CSV file using the standard library.
import sqlite3
import csv
def export_query_to_csv(db_path, query, csv_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute(query)
rows = cursor.fetchall()
column_names = [description[0] for description in cursor.description]
with open(csv_path, 'w', newline='', encodi…
How to Build a CSV Comparison Tool That Highlights Every Changed Cell in Python
Read two CSV files with DictReader, compare cell by cell, and return a list of dictionaries describing each changed cell using only the standard library.
import csv
from pathlib import Path
def csv_cell_diff(file_a: str, file_b: str) -> list[dict]:
rows_a = list(csv.DictReader(Path(file_a).open('r', newline='')))
rows_b = list(csv.DictReader(Path(file_b).open('r', newline='')))
if not rows_a or not rows_b:
return []
columns = list(rows_a[0].key…
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 Filter CSV Rows by Column Value in Python
Filter CSV rows based on a column value condition using the standard csv module and a lambda function.
import csv
def filter_csv(input_file, output_file, column, condition):
with open(input_file, newline='', encoding='utf-8') as infile, \
open(output_file, 'w', newline='', encoding='utf-8') as outfile:
reader = csv.DictReader(infile)
fieldnames = reader.fieldnames
writer = csv.Dict…
How to Generate an Inventory Report of All Files in Python
Walk a directory tree, collect metadata for every file, and write a CSV inventory report using Python's os, pathlib, and csv modules.
import os
import csv
from pathlib import Path
from datetime import datetime
def generate_inventory_report(root_dir: str = "/", output_file: str = "inventory_report.csv"):
headers = ["File Path", "Size (bytes)", "Last Modified", "File Type"]
rows = []
start_time = datetime.now()
for dirpath, dirna…
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.
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…
How to Parse JSON, TXT, and CSV Files in Python
This code provides simple functions to read and parse JSON, text, and CSV files using Python's standard library, returning native data structures.
import json
from pathlib import Path
def parse_json_file(filepath):
"""Read and parse a JSON file, returning its contents."""
path = Path(filepath)
with path.open('r', encoding='utf-8') as f:
return json.load(f)
def parse_txt_lines(filepath):
"""Read a text file and return non-empty stripped …
How to Read a TSV File in Python with csv.DictReader
Read a tab-separated (TSV) file into dictionaries using the csv module's DictReader with a tab delimiter.
import csv
from pathlib import Path
data_file = Path("data.tsv")
# Sample TSV content (tab-separated)
sample = """name\tage\tcity
Alice\t30\tNew York
Bob\t25\tLos Angeles
Carol\t35\tChicago
"""
data_file.write_text(sample)
with data_file.open("r", newline="", encoding="utf-8") as f:
reader = csv.DictReader(f, d…
How to Stream Large CSV Files in Python
Process a large CSV file in memory-efficient chunks using Python's csv module, yielding batches of rows instead of loading everything at once.
import csv
from pathlib import Path
def process_csv_in_chunks(file_path, chunk_size=1000):
"""Yield rows from a large CSV file in chunks without loading all into memory."""
with open(file_path, 'r', newline='') as f:
reader = csv.DictReader(f)
chunk = []
for row in reader:
…
How to Sum a CSV Column by Group in Python
This code reads a CSV string and sums a specified column for each unique value of a group key using the csv module and defaultdict.
import csv
from collections import defaultdict
from io import StringIO
def aggregate_csv(csv_data, group_key, sum_column):
totals = defaultdict(float)
reader = csv.DictReader(StringIO(csv_data))
for row in reader:
key = row[group_key]
totals[key] += float(row[sum_column])
return dict(t…
Join two CSV files on shared key column in Python
Merge rows from two CSV files by a common key column, outputting combined records to a new file.
import csv
def join_csv(file1, file2, key, output="joined.csv"):
# Read first CSV into dict keyed by the join column
with open(file1, newline="") as f1:
reader1 = csv.DictReader(f1)
data1 = {row[key]: row for row in reader1}
# Read second CSV and merge matching rows
with open(file2, n…
Normalize CSV Column Names to snake_case in Python
Convert CSV header names to snake_case using a regular expression and write the updated file in place.
import csv
import re
import sys
def to_snake_case(header):
header = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", header)
header = re.sub(r"[^a-zA-Z0-9]+", "_", header).strip("_").lower()
return header
def normalize_csv_headers(input_path, output_path=None):
with open(input_path, newline="", encoding="utf…
Parse CSV with Custom Delimiter and Quote Character in Python
Reads a CSV string with a custom delimiter and quote character using the csv module, returning a list of rows.
import csv
from io import StringIO
def parse_csv(data, delimiter='|', quotechar='"'):
reader = csv.reader(StringIO(data), delimiter=delimiter, quotechar=quotechar)
rows = [row for row in reader]
return rows
if __name__ == "__main__":
sample = 'Alice|"Smith, Jr."|25\nBob|"Johnson, Sr."|30'
result …
Read Parquet-Like Columnar CSV Chunks in Python
A Python generator that reads a CSV file column-by-column, yielding dictionary chunks where each key points to a list of values—mirroring how Parquet stores data columnar.
```python
import csv
from pathlib import Path
from typing import Iterator, List
def read_parquet_like_columnar(csv_path: str, column_names: List[str], chunk_size: int = 2) -> Iterator[dict]:
"""Read CSV data in columnar chunks, similar to how parquet stores columns."""
csv_file = Path(csv_path)
with csv_f…
Read a CSV File with csv.DictReader in Python
Read a CSV file as a list of dictionaries, using csv.DictReader to map each row to column names.
import csv
from pathlib import Path
def read_csv_with_dictreader(file_path):
data = []
with open(file_path, mode='r', newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
return data
if __name__ == "__main__":
# Cre…
Scrape HTML Tables and Convert Them to CSV Using Beautiful Soup in Python
Scrape a Wikipedia table with Beautiful Soup and write the data to a CSV file using the csv module.
import requests
from bs4 import BeautifulSoup
import csv
url = "https://en.wikipedia.org/wiki/List_of_countries_by_GDP_(nominal)"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
tables = soup.find_all('table', {'class': 'wikitable'})
if tables:
target_table = tables[2]
rows =…
Split CSV Files into Smaller Chunks in Python
Splits a large CSV file into multiple smaller chunk files, preserving the header row in each chunk.
import csv
import os
def split_csv(input_file, chunk_size=1000, output_prefix="chunk"):
"""Split a large CSV file into smaller chunks."""
with open(input_file, 'r', newline='') as infile:
reader = csv.reader(infile)
header = next(reader)
file_count = 1
row_count = 0
…
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.