Python Read File Line by Line with a Generator
To read a file line by line in Python, loop over the open file. It hands over one line at a time, so a large file never has to fit in memory. Wrap the loop in a generator to keep the rest of your program lazy too.
Prerequisites: Python Read File: Reading Text Files and Python Generator Pipeline. Each example first writes a small file, so it runs on its own.
A file hands over one line at a time
An open file is an iterator of lines. next() and for both work on it.
with open("names.txt", "w") as target: target.write("Ada\nBo\nCy\n")with open("names.txt") as file: print(next(file).rstrip("\n")) for line in file: print(line.rstrip("\n"))This prints Ada, Bo, Cy. next(file) reads the first line and the loop carries on from the second. Each line ends with "\n", which rstrip("\n") removes.
file.read() and file.readlines() load the whole file at once. The loop does not.
Yield each line from a generator function
Put the with block and the loop inside a generator. The caller gets clean values and never sees the file.
with open("scores.txt", "w") as target: target.write("12\n7\n30\n")def read_scores(path): with open(path) as file: for line in file: yield int(line)for score in read_scores("scores.txt"): print(score * 2)This prints 24, 14, 60. The file stays open while the generator is paused. It closes when the generator finishes.
Stop early and the rest is never read
from itertools import islicewith open("scores.txt", "w") as target: target.write("12\n7\n30\n18\n5\n")def read_scores(path): with open(path) as file: for line in file: print("reading a line") yield int(line)print(list(islice(read_scores("scores.txt"), 2)))reading a line prints twice, then [12, 7]. The last three lines are never read. A function that returned a list would have read all five.
Keep the with block inside the generator
This function returns a generator expression from inside with. The file closes at return, before any line is requested.
with open("names.txt", "w") as target: target.write("Ada\nBo\n")def broken(path): with open(path) as file: return (line.rstrip("\n") for line in file)for name in broken("names.txt"): # this line raises ValueError: I/O operation on closed file print(name)Use yield inside the with block instead. Then the file is still open each time the generator resumes.
Note: These examples leave out encoding="utf-8" to stay short. Pass it to open() for real files. They also assume the file exists.
See also: Reading a whole file, Python Generator close(): Stopping a Generator.
Your turn
Write the generator shout(path). It yields each line of the file in capitals, without the newline at the end. The loop is supplied.
CAT DOG FISH
with open("pets.txt", "w") as target: target.write("cat\ndog\nfish\n")# Define shout(path) here.for pet in shout("pets.txt"): print(pet)