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.
writeadds none, so you add it yourself. - Opening a missing file for reading raises
FileNotFoundError.
pathlib
pathlib.Path wraps a path in an object, with shortcuts for whole-file work:
from pathlib import Path
p = Path("notes.txt")
p.write_text("hi\n", encoding="utf-8")
print(p.read_text(encoding="utf-8"))
print(p.exists(), p.suffix)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.
The explanation opens here once every check passes.