Files & data
Read and write files safely; parse JSON, CSV, and common text formats.
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.
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", "…
How to Merge Sorted Chunk Files in Python
Merge multiple sorted text files into one sorted output file using a heap for efficient k-way merging.
import heapq
def merge_sorted_chunks(chunks, output_path):
"""Merge multiple sorted iterables into single sorted output file."""
with open(output_path, "w") as out_f:
# Open all chunk files
handles = [open(chunk, "r") for chunk in chunks]
try:
# Heap of (value, index) tupl…
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 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.
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…
Reassemble File Parts into Original File Bytes in Python
Read sorted part files from a directory and concatenate their bytes into the original file.
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:
…
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.