Python Practice › Iterator & Generator Programs › Program 9
Read a file lazily
Write a generator that yields non-empty, stripped lines from a file.
Output
['start', 'step 1', 'end']
Approach
- Loop over the file inside the generator.
Solution
with open("log.txt", "w") as f: f.write("start\n\n step 1 \nend\n") def clean_lines(path): with open(path) as f: for line in f: line = line.strip() if line: yield line print(list(clean_lines("log.txt")))Output
['start', 'step 1', 'end']
Learn the concept
New to this topic? Read the lesson, then come back.