Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
BUILD LAB / PYTHON/ Files with a future
EXPERIMENT 29 / 101

Think in lines, not mountains.

Process a file incrementally instead of loading the whole thing into memory.

ADVANCED LAB
BY NAVAN SAMI◷ 10 MIN READPYTHON 3

01 The idea

A streaming pipeline does a little work for each record and keeps only the state it needs. Iterating over a text file yields one line at a time, unlike read(), which loads all the text. This is helpful when input size grows beyond a comfortable memory budget. The algorithm still has to examine every relevant line; streaming reduces retained data, not the amount of input.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

streaming_large_files.py
from pathlib import Path
path = Path("events.log")
path.write_text("INFO start\nERROR timeout\nINFO retry\nERROR offline\n", encoding="utf-8")
errors = 0
with path.open(encoding="utf-8") as stream:
    for line in stream:
        if line.startswith("ERROR "):
            errors += 1
print(f"errors={errors}")
↳ EXPECTED OUTPUT
errors=2

03 Under the hood

  1. 1

    The fixture is tiny so the example is easy to inspect. The same reading loop works when the input contains many more lines.

  2. 2

    The accumulator errors is constant-size state. Avoid appending every line to a list if you only need a count.

  3. 3

    Line iteration assumes sensible line boundaries. A single enormous line can still use substantial memory; binary chunk processing is a different technique when no line structure exists.

04 Your turn, builder

A SMALL MISSION

Count nonblank lines without collecting them into a list.

Reveal one possible solution +
one_possible_solution.py
from pathlib import Path
path = Path("lines.txt")
path.write_text("Build\n\nTest\n", encoding="utf-8")
with path.open(encoding="utf-8") as stream:
    count = sum(1 for line in stream if line.strip())
print(count)

05 Check your signal

QUICK SIGNAL CHECK

Which operation loads the full file into a string?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.