Reading brings data into a program; writing sends it to a destination. Text streams carry strings, while binary streams carry bytes.
Use files and in-memory streams, keep text and byte counts separate and handle large inputs incrementally.
A log looks identical in two editors, yet one report counts more bytes than the other. Before changing the code, decide what you are measuring: stored bytes, decoded characters or lines. Text mode can transform what you read; binary mode preserves the byte sequence. We will inspect both views of one small file.

Read a Windows log without guessing
A log shipped from a Windows server uses \r\n line endings. Put exactly
four bytes on disk — a, carriage return, line feed, b — and read them
both ways:
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "w.txt"
path.write_bytes(b"a\r\nb")
with open(path, encoding="utf-8") as f:
print(len(f.read()))"How big is this file, and does it use Windows endings?" is a question about
bytes — ask it in "rb" mode, where b"\r\n" in raw is still visible.
"What does line 3 say?" is a question about text — ask it with
encoding="utf-8", where the loop below never sees a stray \r:
Looping the file object reads one line at a time and holds only that line in
memory — read() and readlines() pull the whole file into memory,
which is fine for a small config file but can exhaust memory on a large log. Strip the ending
with rstrip("\n"), never strip(), which would also eat meaningful
leading spaces.
"w" is the dangerous mode: opening for writing empties the file
immediately, before you've written a single byte. If the program crashes
between open and write, the old contents are already gone — lesson 03
fixes that properly. "x" is the polite alternative, for an output that must
never overwrite a previous run's:
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "report.txt"
path.write_text("first run\n", encoding="utf-8")
with open(path, "x", encoding="utf-8") as f:
f.write("second run\n")
print("written")Preparing this topic’s interactive investigation…
Keep the byte count separate from the text count
A file containing é\r\nZ has 5 UTF-8 bytes, 4 Unicode code points before newline translation, and 3 code points after the default text reader changes \r\n to \n. These are different measurements of the same input.
The bytes c3 a9 jointly encode é; neither byte alone is that character. The pair 0d 0a is a newline convention that the default text reader normalizes. newline="" still recognizes line endings but preserves their spelling. This is why CSV readers ask you to open their text stream with that setting.
Streaming also needs a unit. Iterating a file bounds memory by the largest line, not by a fixed number of bytes. One enormous line can still be enormous. Reading binary chunks bounds each chunk, but decoding each chunk independently is unsafe: a boundary can split c3 a9. Use a text stream or an incremental decoder to retain an unfinished character across reads.
Investigate: change the raw bytes to "é\r\nZ\n".encode("utf-8"). Predict the byte count, translated text length and number of iterated lines separately. Then explain why a final newline ends the last line without automatically adding an extra empty line to file iteration. If a report says a file shrank, establish which measurement changed before diagnosing data loss.
Reference: text streams, newline handling and buffering.
Stream a 20 GB telemetry dump in flat memory
Quarry reads files far too big to hold in memory at once, in fixed-size
chunks, using read(size):
read(n) returns at most n bytes, and the last chunk is often
shorter. The only reliable stop signal is an empty result — a short
chunk doesn't mean the end in general, only here, at the real end of the
file. Writing follows the same shape in reverse: write() returns how much
it accepted, which in text mode is a count of characters, not bytes —
only after encoding do they become bytes on disk.
Replay a buffer with StringIO
io.StringIO and io.BytesIO behave like files but live entirely in
memory — useful for testing file-handling code without touching a disk, and
they make a file object's one hidden rule visible: there is a single
cursor, shared by reading and writing. This prints an empty line; fix it
with one call:
Run it — it prints nothing. Explain to yourself where the cursor is, then fix it.
That same shared cursor exists on a real file opened "r+" or "w+".
tell() reports its position, seek(n) moves it. Step through a chunked
read and watch the position march forward four bytes at a time:
The trace shows the same rule the telemetry dump relied on: read(4) returns
at most four bytes, the last chunk is shorter, and the loop stops on an
empty result, never on "the chunk was short".
One warning about tell(): only on a binary file is its position a byte
offset you can do arithmetic on. On a text file it's an opaque cookie you may
only hand back to seek(), because decoding and newline translation mean
"character 7" and "byte 7" aren't the same place. When Quarry needs real
offsets, it opens in "rb".
Quick practice
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "a.log"
with open(path, "w", encoding="utf-8") as f:
f.write("first\n")
with open(path, "a", encoding="utf-8") as f:
f.write("second\n")
print(repr(path.read_text(encoding="utf-8")))line = " indented value\n"
print(repr(line.strip()), repr(line.rstrip("\n")))import io
buf = io.StringIO("abcdef")
buf.seek(2)
first = buf.read(2)
buf.write("XY")
buf.seek(0)
print(first, buf.read())Run it. The size may read 0. Close the file (or use `with`) before measuring it.
🎯 Your turn
Build read_source(files, name):
read_source({"a.log": "one\r\ntwo\r\n"}, "a.log")→{"bytes": 10, "lines": 2, "first": "one", "crlf": True}read_source({"c.txt": "café\nnaïve\n"}, "c.txt")→{"bytes": 13, "lines": 2, "first": "café", "crlf": False}
Hint — read once in "rb" for size and endings, once in text mode with
encoding="utf-8" for lines.
Then press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write bytes_on_disk(text): write text to a file in a temporary folder with encoding="utf-8", then return the file's size in bytes (path.stat().st_size). bytes_on_disk("é") → 2.
Write tail(text, n): plant text as a file, read it back in text mode, and return its last n lines without their line endings. tail("a\nb\nc\n", 2) → ["b", "c"].
Big files are read a chunk at a time. Write chunk_sizes(text, size): plant text, open it in binary mode, call f.read(size) until it returns empty bytes, and return the list of chunk lengths. chunk_sizes("abcdefghij", 4) → [4, 4, 2].
A yard mixes Windows (\r\n), old Mac (\r) and Unix (\n) endings. Write to_unix(text): plant text, read it back in text mode (which translates all three to \n), write the result to a second file with newline="\n", then read that second file in BINARY mode and return its bytes decoded as UTF-8. to_unix("a\r\nb\rc\n") → "a\nb\nc\n".
To jump straight to line 50,000 later, Quarry records where every line starts. Write line_offsets(text): plant text, open it in BINARY mode, and return [[offset, line], ...] where offset is f.tell() before each readline() and line is that line decoded as UTF-8 without its ending (\r\n or \n). Then prove the index works: for the LAST entry, seek to its offset and check a fresh readline() gives the same line — return [] if it doesn't.
Quarry's code review rule is: every text-mode open() passes encoding= explicitly. A colleague says the default has always worked on their laptop. Explain what the default actually is, how the same code can break on another machine, and why the failure is especially nasty.