Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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 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 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 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…
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 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…
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
…
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:…
Browse by section
Each section groups closely related Python snippets.
Files & data — Python code examples
What you will find here
This page collects files & data 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.