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

Python I/O: Streaming, Buffering, Async Reads

Python I/OđŸŸĸ Free Lesson

Python I/O: Streaming, Buffering, Async Reads

Most slow data scripts are not slow because Python parses text badly. They are slow because the whole file was read into a list, because every small write hit the disk on its own, or because a program that waits on a socket spent its time blocked while a single thread did nothing. I/O work rewards a clear model of where the bytes actually travel: from the operating system page cache into a user-space buffer, then into Python objects, and eventually back the other way.

This lesson builds that model, then applies it three times. First to line-by-line streaming that keeps memory flat no matter how large the input grows. Second to buffered and chunked writes that avoid a system call per item. Third to asynchronous and threaded approaches, with an honest account of when they help and when they only add complexity.

What You'll Learn

  • 1Explain the layers between a Python file object and the kernel
  • 2Stream huge files with iterators and generators without growing memory
  • 3Batch binary and text output so system calls stay rare
  • 4Decide between native async, thread offloading, and plain blocking code

The four layers between your code and the disk

Calling open() does not give you a direct line to the disk. It gives you a buffered reader or writer sitting on top of a file descriptor, which sits on top of the kernel's page cache, which sits on the actual device. Text mode adds another layer on top: an incremental decoder that turns bytes into strings and may hold a partial multi-byte character between calls.

Each layer exists to amortize cost. The user-space buffer means a loop reading one line at a time issues a read syscall only when the buffer runs dry, typically every eight kilobytes or more. The page cache means a file read twice in a row never touches the device the second time. The incremental decoder means you can iterate lines of UTF-8 without ever handling a split character yourself.

LayerOwned byTypical sizeWhat it saves
Kernel page cacheOperating systemMegabytes to gigabytesRepeated disk reads
User-space bufferPython file object8 KB to 64 KB, configurableSystem calls per small read
Incremental decoderText-mode wrapperA few bytesSplit multi-byte characters
Your objectsApplication codeWhatever you buildNothing; this is the cost

The practical consequence is that for line in handle is already efficient. Reading byte by byte with handle.read(1) is not, because each call turns into Python-level work even though the buffer avoids a syscall.

Streaming a file that does not fit in memory

A file object is an iterator, and that single fact replaces most hand-written chunking code. Iterating yields lines lazily, so peak memory stays proportional to the longest line rather than the file. Wrapping the iteration in a generator pushes the same guarantee into the rest of the pipeline, letting callers compose filtering and transformation without ever materializing a list.

python
from collections import Counter
import tracemalloc


def parse_events(path, level="ERROR"):
    with open(path, encoding="utf-8", errors="replace") as handle:
        for lineno, line in enumerate(handle, start=1):
            if level not in line:
                continue
            _, _, message = line.partition(level)
            yield lineno, message.strip()


def count_by_service(path):
    counts = Counter()
    for lineno, message in parse_events(path):
        service = message.split()[0] if message.split() else "unknown"
        counts[service] += 1
    return counts


if __name__ == "__main__":
    tracemalloc.start()
    counts = count_by_service("app.log")
    current, peak = tracemalloc.get_traced_memory()
    print(counts.most_common(5))
    print(f"peak {peak / 1_048_576:.2f} MiB")
    tracemalloc.stop()

Two habits keep this honest. Use errors="replace" on logs you do not fully control so a stray byte cannot raise mid-run. And run the counter under tracemalloc once: the peak number tells you whether you truly streamed or accidentally built an intermediate list through something like a comprehension that looks lazy but is not.

Buffering writes on purpose

Writing is where buffering matters most, because the default line-buffered or block-buffered behavior can still turn into a syscall per record when the object is flushed at the wrong moment. Binary mode with an explicit buffer size gives you predictable batching: accumulate into a bytearray, flush when the accumulator passes a threshold, and finish with one final write.

python
from io import BytesIO
import json
import time


def export_ndjson(records, path, flush_every=4096):
    pending = bytearray()
    written = 0
    with open(path, "wb", buffering=1 << 16) as out:
        for record in records:
            pending.extend(json.dumps(record, separators=(",", ":")).encode("utf-8"))
            pending.extend(b"\n")
            if len(pending) >= flush_every:
                out.write(pending)
                written += len(pending)
                pending.clear()
        if pending:
            out.write(pending)
            written += len(pending)
    return written


def build_records(n=500_000):
    for i in range(n):
        yield {"id": i, "name": f"row-{i}", "amount": i * 3}


if __name__ == "__main__":
    started = time.perf_counter()
    size = export_ndjson(build_records(), "out.ndjson")
    print(f"{size} bytes in {time.perf_counter() - started:.2f}s")

A BytesIO object behaves the same way without touching the filesystem, which makes it useful as a staging buffer, a fake file in tests, or a place to build a payload you will hand to an HTTP client in one piece.

Overlap, not magic: threads, processes, and async

Asynchronous I/O does not make a single read faster. It lets one thread keep working while another operation waits, which is valuable when a program talks to many sockets or many remote files at once. For local disk, the operating system already caches aggressively, and Python's file API is blocking by nature, so wrapping file reads in async generally buys nothing unless the file lives behind a network filesystem.

The honest decision table looks like this. If work is CPU-bound after the read, use processes to get past the global interpreter lock. If work is mostly waiting on a handful of blocking calls that do not release the GIL, a small thread pool is often simpler than an event loop. If you are already inside an async application and the operation supports it, offload the blocking call to a thread executor rather than blocking the loop.

python
import asyncio
from concurrent.futures import ThreadPoolExecutor
import pathlib


def read_summary(path):
    text = pathlib.Path(path).read_text(encoding="utf-8")
    lines = text.splitlines()
    return path.name, len(lines), sum(len(x) for x in lines)


async def gather(paths, max_workers=8):
    loop = asyncio.get_running_loop()
    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        tasks = [loop.run_in_executor(pool, read_summary, p) for p in paths]
        return await asyncio.gather(*tasks)


if __name__ == "__main__":
    sample = [pathlib.Path(f"part-{i}.txt") for i in range(8)]
    print(asyncio.run(gather(sample)))

The executor is the important part: file reads block, and blocking inside a coroutine stalls every other task. Moving them to a worker thread restores the concurrency the event loop promises.

Parsers that keep the streaming guarantee

Streaming only helps if the parser is also incremental. The standard library gives you three that are: csv.reader yields one row per call, json.loads parses one complete line when the file is in JSON Lines form, and line.split or partition handles delimiter formats without allocating more than the current line. What breaks the guarantee is a parser that needs the entire document, such as a single large XML or JSON array, because it cannot produce a value until it has seen the end of the input.

For those documents the practical options are to ask the producer for a line-oriented format, to use an incremental parser that emits events as it goes, or to accept the memory cost deliberately and document it. Pretending to stream while calling a whole-document parser is worse than admitting the materialization, because the memory profile of the job becomes a surprise at the next scale-up.

A related trap is decompression. A gzip file can be read line by line through gzip.open, which decompresses incrementally, but the decompressor itself holds a window of recent bytes, so peak memory is no longer one line: it is one line plus the window. That is usually fine, and it is worth knowing when a job that ran comfortably at one gigabyte starts failing at three.

Choosing a strategy for a real pipeline

For a one-shot batch job over local files, plain synchronous streaming with a generous buffer is usually both the fastest and the easiest code to read. For a service that fans out to object storage or a database, async or a bounded thread pool earns its complexity by overlapping latency. For CPU-heavy parsing after the read, no I/O technique will help; that work belongs in a process pool or a faster parser.

Whatever you choose, keep the measurement. Record wall time, peak memory with tracemalloc, and the number of writes. A pipeline that streams in constant memory and issues a handful of system calls per megabyte will keep behaving the same way when the input grows a hundredfold, which is the property that matters at production scale.

Common Mistakes

Reading a huge file with readlines or a list comprehension and then filtering

Fix: Iterate the file object directly or yield through a generator so only one line lives in memory at a time

Awaiting file operations inside a coroutine expecting them to become non-blocking

Fix: Standard file calls block the event loop; run them in a thread executor or use an async-native library

Opening a file in text mode for bulk binary output

Fix: Use binary mode with an explicit buffer size and encode yourself, otherwise the codec layer adds cost and surprises

Writing one small record at a time without flushing control

Fix: Accumulate into a bytearray and flush at a threshold so system calls stay rare and predictable

Best Practices

  • Set buffering explicitly on files you write in bulk instead of relying on the default
  • Pass the replace error policy when parsing logs or user-supplied text that may not be valid UTF-8
  • Compose generators so each stage stays lazy and memory remains flat end to end
  • Profile peak memory with tracemalloc after any change that claims to stream
  • Measure system call counts with a tool such as strace or dtrace when throughput is the goal

Interview Questions

Q1: Why is iterating a file object memory-efficient?

The file object is an iterator backed by a fixed-size user-space buffer. Each next call refills that buffer from the operating system only when it runs empty, so memory depends on the longest line rather than the file size.

Q2: When does async file I/O help?

Only when the underlying operation can be awaited without blocking, or when blocking calls are moved to worker threads. For local synchronous files on a single thread it adds overhead without overlap.

Q3: What is the difference between flush and close?

Flush pushes buffered bytes to the operating system and keeps the file usable. Close flushes and then releases the descriptor. Data written but not flushed may still be lost if the process dies.

Key Takeaways

  • Python file objects already buffer; most slowness comes from building full lists instead
  • Generators plus direct iteration give constant memory regardless of input size
  • Batch binary writes into a bytearray and flush at a threshold to cut system calls
  • Async helps only by overlapping waits, and blocking file calls must leave the event loop
  • Keep wall time, peak memory, and syscall counts as the three numbers that prove a change
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

Related Tutorials

Content with similar topics across other courses

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement