Reference library

Files & data

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

4 matches
Files & data easy

Create an In-Memory SQLite Table and Query It in Python

This code creates an in-memory SQLite database, defines an employees table, inserts sample rows, and runs a filtered query with sorted results.

sqlite in-memory database
Python
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()

cursor.execute("""
    CREATE TABLE employees (
        id INTEGER PRIMARY KEY,
        name TEXT NOT NULL,
        department TEXT NOT NULL,
        salary REAL
    )
""")

employees = [
    (1, "Alice", "Engineering", 95000),
    (2, "Bob", "…
11 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 a Dict to a Pretty JSON File with Indent in Python

Serializes a Python dictionary to a readable JSON file using json.dump with indentation and sorted keys, then prints the file contents to stdout.

json files serialization
Python
import json
from pathlib import Path

data = {
    "name": "Python",
    "version": 3.12,
    "features": ["simple", "readable", "powerful"],
    "nested": {"creator": "Guido van Rossum", "year": 1991}
}

output_path = Path("output.json")

with output_path.open("w", encoding="utf-8") as f:
    json.dump(data, f, inden…
14 0 Open
Files & data easy

Reassemble File Parts into Original File Bytes in Python

Read sorted part files from a directory and concatenate their bytes into the original file.

file handling binary byte concatenation
Python
import os
import sys
from pathlib import Path

def reassemble_parts(parts_dir: Path, output_path: Path) -> int:
    """
    Reassemble file parts into the original file.

    Args:
        parts_dir: Directory containing the part files
        output_path: Path where the reassembled file will be written

    Returns:
…
12 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.