Think in lines, not mountains.
Process a file incrementally instead of loading the whole thing into memory.
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.
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}")errors=2
03 Under the hood
- 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
The accumulator errors is constant-size state. Avoid appending every line to a list if you only need a count.
- 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
Count nonblank lines without collecting them into a list.
Reveal one possible solution +
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
Which operation loads the full file into a string?
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 ↗.