Read and Write Files Incrementally
Core idea
A text file is iterable over lines. read() consumes remaining text, readline() reads one line and returns an empty string at end of file, and write() writes text without adding a newline. Line iteration avoids materializing every line at once.
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "rows.txt" p.write_text("red\n\nblue\n", encoding="utf-8") with p.open(encoding="utf-8") as f: print(sum(bool(line.strip()) for line in f))Whitespace-only rows are skipped by the predicate.
Write explicit line endings
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "report.txt" with p.open("w", encoding="utf-8", newline="\n") as f: f.writelines(["one\n", "two\n"]) with p.open(encoding="utf-8") as f: print(repr(f.readline())) print(repr(f.read()))writelines does not insert separators; the supplied newline characters separate the rows.
Common mistake
Do not use read() for an unbounded input. strip() removes surrounding whitespace, not just line endings; preserve significant spaces when needed.
Practice
Write three lines in a temporary file, count lines beginning with A and test an empty file.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
File iteration
Check your understanding of reading and writing files.
What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "a" p.write_text("a\nb\n", encoding="utf-8") with p.open(encoding="utf-8") as f: print(len(list(f)))What is printed?
from pathlib import Pathfrom tempfile import TemporaryDirectory
with TemporaryDirectory() as folder: root = Path(folder) p = root / "a" p.write_text("", encoding="utf-8") with p.open(encoding="utf-8") as f: print(repr(f.readline()))What does writelines add automatically?
Which technique avoids reading all rows into a list?