Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
Build a File Index by Relative Path Hash Map in Python
Recursively walk a directory and map normalized relative paths to absolute file paths using a defaultdict hash map.
import os
from collections import defaultdict
def build_file_index(root_dir):
index = defaultdict(list)
for dirpath, dirnames, filenames in os.walk(root_dir):
for filename in filenames:
full_path = os.path.join(dirpath, filename)
relative_path = os.path.relpath(full_path, roo…
Compress and Extract ZIP Files Programmatically in Python
Create a ZIP archive with in-memory files and extract its contents to a directory using Python's stdlib zipfile and pathlib modules.
import zipfile
from pathlib import Path
import tempfile
import os
def create_sample_zip(zip_path: str, files: dict) -> None:
"""Create a ZIP file containing the given files (name -> content mapping)."""
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for filename, content in files.ite…
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:
…
Generate Timesheet Reports from Daily Logs in Python
Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.
import json
from pathlib import Path
from collections import defaultdict
def generate_timesheet_report(daily_logs: list[dict]) -> str:
"""
Generate a timesheet report from daily log entries.
Args:
daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
Returns:
…
How to Compress a String to Gzip Bytes in Python
Compress a string into gzip-compressed bytes entirely in memory using the standard library gzip module.
import gzip
def compress_to_gzip_bytes(data: str, encoding: str = "utf-8") -> bytes:
"""Compress a string to gzip-compressed bytes in memory."""
return gzip.compress(data.encode(encoding))
if __name__ == "__main__":
original = "Hello, world! " * 10
compressed = compress_to_gzip_bytes(original)
pr…
How to Decompress a gzip File in Python
This code provides a function to decompress a .gz file, writing the decompressed content to a new file and returning the text, using the gzip standard library module.
import gzip
from pathlib import Path
def decompress_gzip(filepath: str, output_path: str | None = None) -> str:
"""Decompress a .gz file and return the decompressed content."""
input_path = Path(filepath)
if output_path is None:
output_path = str(input_path.with_suffix(""))
with gzip.open…
How to List Tar Archive Contents in Python
Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.
import tarfile
from pathlib import Path
def list_tar_contents(archive_path):
"""List all entries in a tar archive."""
entries = []
with tarfile.open(archive_path, "r") as tar:
for member in tar.getmembers():
entry_type = "dir" if member.isdir() else "file"
entries.append(f"…
How to Load a YAML Subset in Python Without PyYAML
Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.
import re
from pathlib import Path
def load_yaml_subset(path):
"""Load a flat YAML file (key: value) without external dependencies."""
data = {}
with open(path, 'r', encoding='utf-8') as f:
for line in f:
# Skip empty lines and comments
line = line.strip()
if no…
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 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 Parse XML Attributes into a Flat Dictionary in Python
Parses XML elements and attributes using ElementTree, building a flat dictionary keyed by element attributes.
import xml.etree.ElementTree as ET
xml_data = """<root>
<book id="1" category="fiction" price="9.99">
<title>The Catcher</title>
</book>
<book id="2" category="nonfiction" price="12.50">
<title>Deep Learning</title>
</book>
</root>"""
def parse_xml_attributes(xml_string):
root = E…
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 Sort Files by Name and Size in Python
Sort a list of file dictionaries by name then size using Python's sorted() with a lambda key.
from pathlib import Path
def sort_files_data(files):
"""Sort a list of file dictionaries by name, then by size."""
return sorted(files, key=lambda f: (f["name"], f["size"]))
if __name__ == "__main__":
files_data = [
{"name": "report.pdf", "size": 2048},
{"name": "data.csv", "size": 1024},…
How to Write Simple XML Documents with ElementTree in Python
Create well-structured XML documents in memory using Python's built-in ElementTree module, complete with nested elements, attributes, and text content.
import xml.etree.ElementTree as ET
def create_xml_document():
# Create root element
root = ET.Element("catalog")
# Create a book element with attributes and children
book1 = ET.SubElement(root, "book", id="bk101")
ET.SubElement(book1, "author").text = "Gambardella, Matthew"
ET.SubElement(…
Read SQLite database with sqlite3 module in Python
Connect to a SQLite database and query rows with the standard library sqlite3 module, returning results as dictionaries.
import sqlite3
from pathlib import Path
# Create an in-memory database and a sample table
connection = sqlite3.connect(":memory:")
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
department TEXT NOT NULL,
salary REAL
)
""")
# Inser…
Read an XML File with xml.etree.ElementTree in Python
Parse an XML file and print its root and child elements using the standard library's xml.etree.ElementTree module.
import xml.etree.ElementTree as ET
def read_xml_file(file_path):
"""Read an XML file and print its structure."""
tree = ET.parse(file_path)
root = tree.getroot()
print(f"Root element: {root.tag}")
for child in root:
print(f"Child element: {child.tag}, text: {child.text}")
if __name__ ==…
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.
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.