Readings, One Line at a Time

Python for AIMedium+10 XP+10

Readings, One Line at a Time

A sensor writes one reading per line to a text file. Some lines are notes that start with #, and some lines are blank.

Task: write a generator function readings(path) that opens the file and hands out each reading as a float, one at a time, in file order.

  • Skip blank lines (including lines that are only spaces).
  • Skip lines whose first non-space character is #.
  • Readings may have spaces around them.

The starter code includes a helper, make_file(path, text), that writes a test file and returns its name.

Examples

list(readings(make_file('demo.txt', '3.5\n# calibrated\n\n 7\n')))
returns [3.5, 7.0]
list(readings(make_file("r1.txt", "3.5\n# calibrated\n\n 7\n")))
returns [3.5, 7.0]
list(readings(make_file("r2.txt", "")))
returns []

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run