Command Palette

Search for a command to run...

Hectal
Phase 7: Errors, Files and Data Formats
Python · Exercise 3 of 7 PreviousNext
Intermediate

Write a file and count its lines

Write save_lines(path, lines) that writes each string in the list lines to the file at path, one per line (each line ends with "\n"), in UTF-8.

Write count_nonempty(path) that returns how many lines in the file are not empty after stripping spaces. A line with only spaces does not count. Loop over the file line by line instead of using read().

What Check tests

  1. save_lines creates the file with the lines
  2. count_nonempty counts 2 for two lines
  3. Blank lines are not counted
  4. Non-English text survives
  5. An empty list gives an empty file and a count of 0
  6. Saving again replaces the old content

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.