21. Read a File in Chunks
Difficulty: Easy · Topic: Generators & iterators
A log file is too big to load at once. Write a generator read_chunks(f, size): f is an open text file (anything with .read(n)). Yield its content size characters at a time, in order, until the end of the file; the last chunk may be shorter.
- Read lazily: each chunk is read from the file only when the caller asks for it.
- A
sizebelow 1 raisesValueError.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
import io
list(read_chunks(io.StringIO("abcdefg"), 3))Expected: ['abc', 'def', 'g']
Hints
Hint 1
A function containingyield returns a generator: its body runs only as the caller iterates.Hint 2
f.read(size) returns '' at the end of the file.Hint 3
while chunk := f.read(size): yield chunk reads and stops in one line.Learn the concepts
- Files, JSON, CSV and dates · 8 min read. Read files line by line, JSON and CSV, ISO dates, strptime codes, time zones and zoneinfo.
- Generators and lazy evaluation · 6 min read. yield, constant-memory pipelines, endless inputs and the one-pass rule.
More Python problems
- Batch an Iterable · Easy
- A Generator Pipeline · Medium
- Moving Average over a Stream · Medium
- Flatten Any Iterable Lazily · Medium
- A Re-iterable Date Range · Medium
- Merge Sorted Streams Lazily · Hard