Read a file lazily

EasyIterator & Generator Programs · 9 of 20

Write a generator that yields non-empty, stripped lines from a file.

Advertisement
Output
['start', 'step 1', 'end']

Approach

  1. Loop over the file inside the generator.

Solution

Python
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.

More iterator & generator programs

← All 20 Iterator & Generator Programs

Leave a Comment