Reference library

Files & data

Read and write files safely; parse JSON, CSV, and common text formats.

17 matches
Files & data easy

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.

os.walk file-index defaultdict
Python
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…
18 0 Open
Files & data easy

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.

zip compression file-io
Python
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…
99 0 Open
Files & data easy

Convert CSV Files to JSON in Python

Convert a CSV file to a JSON file using Python's built-in csv and json modules.

csv json conversion
Python
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:
      …
93 0 Open
Files & data easy

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.

timesheet reporting aggregation
Python
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:
       …
45 0 Open
Files & data easy

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.

gzip compression bytes
Python
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…
13 0 Open
Files & data easy

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.

gzip decompression file-handling
Python
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…
12 0 Open
Files & data easy

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.

tarfile archive filesystem
Python
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"…
11 0 Open
Files & data easy

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.

yaml parsing stdlib
Python
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…
18 0 Open
Files & data easy

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.

json csv file parsing
Python
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 …
14 0 Open
Files & data easy

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.

pathlib filesystem file-paths
Python
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(…
13 0 Open
Files & data easy

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.

xml elementtree parsing
Python
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…
14 0 Open
Files & data easy

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.

csv tsv file-io
Python
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…
14 0 Open
Files & data easy

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.

sorting files lambda
Python
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},…
13 0 Open
Files & data easy

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.

xml elementtree serialization
Python
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(…
13 0 Open
Files & data easy

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.

sqlite database stdlib
Python
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…
17 0 Open
Files & data easy

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.

xml elementtree file-io
Python
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__ ==…
12 0 Open
Files & data easy

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.

csv file-splitting batch-processing
Python
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
  …
42 0 Open

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.