🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Streaming, Buffering, and Memory-Mapped File I/O

Python I/OFile I/OđŸŸĸ Free Lesson

Streaming, Buffering, and Memory-Mapped File I/O

The most common way a Python data job dies is one line: data = f.read(). It works in development on a 40 MB sample, and it fails in production on a 12 GB export — often not with a clean error, but with the operating system killing the process for using too much memory. File I/O in Python is almost always a memory decision before it is a speed decision: whether you hold the whole thing, hold it in pieces, or let the kernel hand you pages on demand.

This lesson covers the three strategies that cover nearly every case — streaming with generators, explicit buffering with the io module, and memory-mapping for random access — plus the compression and encoding details that decide whether your bytes mean what you think they mean.


The cost model you are optimising against

A file read has three layers: your Python call, the buffered object Python maintains, and the kernel's page cache. Calling read(n) does not hit the disk every time; it copies from a buffer that the interpreter refills in larger blocks. That means the naive question "should I buffer?" is usually already answered — Python buffers for you — and the real questions are about how much you materialise at once and whether you need random or sequential access.

Sequential access belongs to generators: yield a chunk, process it, let it go. Random access belongs to mmap, which exposes the file as a bytes-like object backed by the page cache, so touching a byte at offset N faults that page in rather than loading a prefix of the file.

python
from pathlib import Path

def stream_bytes(path: Path, chunk_size: int = 1 << 20):
    """Yield 1 MiB chunks; peak memory stays at one chunk regardless of file size."""
    with path.open("rb") as fh:
        while True:
            chunk = fh.read(chunk_size)
            if not chunk:
                return
            yield chunk

def checksum(path: Path) -> int:
    import hashlib
    h = hashlib.sha256()
    for chunk in stream_bytes(path):
        h.update(chunk)
    return int(h.hexdigest(), 16)

The generator is what makes this safe: checksum never holds more than one chunk, so a 20 GB file and a 2 MB file cost the same memory. Note the if not chunk: return test — read returns an empty bytes object exactly once at end of file, and forgetting that guard is the classic infinite loop.

Line streaming and csv at scale

Text has its own streaming idiom, and it is simpler than the binary version: iterating a file object yields lines with the newlines intact, and the io module handles encoding and newline translation for you. csv.reader accepts any iterable of lines, so a multi-gigabyte CSV can be reduced without ever existing in memory as one string.

python
import csv

def stream_rows(path, encoding="utf-8"):
    with open(path, newline="", encoding=encoding, errors="replace") as fh:
        for row in csv.DictReader(fh):
            yield row

def monthly_totals(path):
    totals = {}
    for row in stream_rows(path):
        month = row["placed_at"][:7]
        totals[month] = totals.get(month, 0.0) + float(row["total"])
    return totals

newline="" is not a stylistic quirk — without it, Python performs universal newline translation that can corrupt embedded newline characters inside quoted fields, producing rows that silently shift. errors="replace" is a deliberate policy choice: a byte that is not valid in the declared encoding becomes a replacement character instead of raising mid-import, and you decide afterwards whether that is acceptable for the field in question.

In-memory buffers and the io module

The io module provides file-like objects that are not files at all. BytesIO and StringIO give you the same interface for data already in memory, which is invaluable for testing code that expects a file handle, for building a document before writing it once, and for handing a seekable stream to a library that insists on one.

ObjectBackingSeekableTypical use
open(path, "rb")Kernel page cacheYesOrdinary file access
io.BytesIO(initial)Heap bytesYesTest doubles, staged output
io.StringIO(text)Heap textYesBuilding CSV or logs in memory
zipfile.ZipFile memberCompressed archiveYesReading one entry without extraction
tempfile.SpooledTemporaryFileDisk after a thresholdYesStreams that may stay small
python
import io
import csv

def render_csv(rows, max_in_memory: int = 1 << 20) -> bytes:
    buf = io.SpooledTemporaryFile(max_size=max_in_memory, mode="w+", newline="", encoding="utf-8")
    try:
        writer = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
        writer.writeheader()
        writer.writerows(rows)
        buf.seek(0)
        return buf.read().encode("utf-8")
    finally:
        buf.close()

SpooledTemporaryFile is the pragmatic middle path: small outputs stay on the heap for speed, and anything past the threshold rolls over to a temporary file so memory stays bounded. It is the right default for report generation where the typical case is small but the tail case is not.

Memory-mapping for random access

mmap maps a file into the process address space. Reading a byte at offset ten million faults in the page that contains it — not the ten million bytes before it — which makes it the tool of choice for index files, database-like lookups over a flat file, and any pattern where you jump around rather than sweep end to end.

python
import mmap

def find_all(path: Path, needle: bytes, window: int = 1 << 22) -> list[int]:
    offsets = []
    with path.open("r+b") as fh:
        if path.stat().st_size == 0:
            return offsets
        with mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) as mm:
            pos = 0
            while True:
                found = mm.find(needle, pos)
                if found == -1:
                    return offsets
                offsets.append(found)
                pos = found + 1

Two cautions. The mapping holds a reference to the file, so it must be closed — the with form handles that, and forgetting it leaks descriptors that eventually exhaust the process limit. And an empty file cannot be mapped at all on most platforms, hence the explicit size check; a zero-byte file is a real case in data pipelines, not an edge-case curiosity.

Compression and encoding without surprises

Compressed formats change the access pattern: gzip is inherently sequential, because decompressing byte N requires everything before it, so pairing gzip with random access is a category error. Python's gzip and bz2 modules accept the same file-like interface, which means the streaming code above works unchanged once you open the right handle.

python
import gzip
import shutil

def gunzip_line_count(path) -> int:
    with gzip.open(path, "rt", encoding="utf-8", errors="replace") as fh:
        return sum(1 for _ in fh)

def transcode(src: Path, dst: Path, from_enc="latin-1", to_enc="utf-8") -> int:
    written = 0
    with open(src, "r", encoding=from_enc, errors="replace") as fin, \
         gzip.open(dst, "wt", encoding=to_enc) as fout:
        for line in fin:
            fout.write(line)
            written += 1
    return written

On the encoding side, the rule is to state the encoding explicitly at every boundary. Python 3's default text encoding follows the platform, so a file written on one machine and read on another can differ without any code change. Declare encoding="utf-8" at the open call, and treat a decode failure as data you must decide about, not as an exception to silence globally with a bare errors="ignore".

Choosing a strategy, then measuring

Access patternStrategyMemoryNotes
Sequential scan, whole fileChunked generatorOne chunkDefault choice for large inputs
Sequential scan, line recordsFile iteration plus csvOne lineNewlines inside quotes need care
Random reads by offsetmmapPage cacheFails on empty files
Output built incrementallySpooledTemporaryFileBoundedRolls to disk past the threshold
Small file, many usesRead into memory onceWhole fileSimplest when it fits
Compressed archivegzip / bz2 handleChunkSequential only for gzip

Before optimising any of this, measure: wrap the section in time.perf_counter, watch peak memory with tracemalloc, and confirm the bottleneck is actually I/O rather than parsing. A generator that streams perfectly but calls a per-row regex compilation is still slow, and no amount of buffering work will fix that — but at least you will know which half of the program to rewrite.

Common Mistakes

Calling f.read() on files that may grow past available memory

Fix: Stream with a generator and a fixed chunk size so peak memory stays flat

Omitting newline='' when opening a CSV for reading

Fix: Pass newline='' so quoted fields containing newlines are not corrupted

Relying on the platform default text encoding

Fix: State encoding='utf-8' explicitly at every open call

Memory-mapping a possibly empty file

Fix: Check the size first and return early — mmap rejects zero-length files

Pairing gzip streams with random access

Fix: Decompress to a seekable form first, or accept sequential-only processing

Best Practices

  • Default to streaming and switch to full reads only when the file is known to be small
  • Keep the chunk size in a named constant so it can be tuned without hunting through code
  • Use SpooledTemporaryFile for outputs whose size is unpredictable
  • Close or use context managers for every mmap and file handle — descriptors are finite
  • Profile with tracemalloc before optimising I/O; the bottleneck is often parsing

Key Takeaways

  • File I/O in Python is a memory decision first: materialise less, stream more
  • Generators make peak memory independent of file size when the access is sequential
  • io.BytesIO, StringIO, and SpooledTemporaryFile give file semantics without a file
  • mmap delivers efficient random access but rejects empty files and must be closed
  • Declare encodings explicitly and decide, rather than inherit, how decode errors behave
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement