Skip to content

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.

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 1A function containing yield returns a generator: its body runs only as the caller iterates.
Hint 2f.read(size) returns '' at the end of the file.
Hint 3while chunk := f.read(size): yield chunk reads and stops in one line.

Learn the concepts

More Python problems

All Python problems