Reference library

Files & data

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

7 matches
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

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 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 medium

How to Memory Map Large Files Read-Only in Python

This code demonstrates reading only the tail of a large file using a read-only memory map (mmap) to avoid loading the entire file into memory.

mmap file-io memory-efficient
Python
import mmap
import os

def read_tail_with_mmap(filepath, bytes_from_end=64):
    """Read the last bytes of a large file using a read-only mmap."""
    file_size = os.path.getsize(filepath)
    start = max(0, file_size - bytes_from_end)

    with open(filepath, "rb") as f:
        with mmap.mmap(f.fileno(), length=0, a…
12 0 Open
Files & data easy

How to Serialize a Python Object to Pickle Bytes in Memory

Serialize a Python object to pickle bytes in memory with pickle.dumps, then deserialize it back with pickle.loads and verify the roundtrip.

pickle serialization bytes
Python
import pickle

class Person:
    def __init__(self, name, age, skills):
        self.name = name
        self.age = age
        self.skills = skills

def main():
    person = Person("Alice", 30, ["Python", "SQL", "Docker"])
    
    # Serialize to bytes in memory
    pickle_bytes = pickle.dumps(person)
    
    print(…
16 0 Open
Files & data medium

How to Stream Large CSV Files in Python

Process a large CSV file in memory-efficient chunks using Python's csv module, yielding batches of rows instead of loading everything at once.

csv streaming memory-efficient
Python
import csv
from pathlib import Path

def process_csv_in_chunks(file_path, chunk_size=1000):
    """Yield rows from a large CSV file in chunks without loading all into memory."""
    with open(file_path, 'r', newline='') as f:
        reader = csv.DictReader(f)
        chunk = []
        for row in reader:
            …
12 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

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.