PythiloLesson 25 of 30 · progress kept in this browser

Reading and writing files

open returns a file object. Use with so it closes even if an error happens.

with open("notes.txt", "w",
          encoding="utf-8") as f:
    f.write("first\n")

with open("notes.txt",
          encoding="utf-8") as f:
    for line in f:
        print(line.rstrip("\n"))
  • Mode "r" reads and is the default. "w" replaces the file. "a" appends.
  • Always pass encoding="utf-8", so text behaves the same everywhere.
  • Each line you iterate over keeps its newline. write adds none, so you add it yourself.
  • Opening a missing file for reading raises FileNotFoundError.
Your task

Write save_lines(path, lines) writing each string on its own line, replacing any existing file. Write count_nonblank(path) returning how many lines contain something other than whitespace, or 0 if the file does not exist.