These questions follow Files and Persistence. Work in a folder you can afford to make a mess in — several of these questions create files, and one of them is about destroying one.

Reading and writing

  1. What do the three modes "r", "a", and "w" do? Which one can lose data, and how?
  2. What is in notes.txt after this runs, exactly?
    with open("notes.txt", "w") as file:
        file.write("first")
        file.write("second")
  3. Rewrite question 2 so the file contains two separate lines, then read the file back and print each line without a blank line between them.
  4. What does this print the very first time it is run in a new folder, and why is that not an unusual case?
    with open("weights.txt", "r") as file:
        print(file.read())

Doing something useful

  1. Handle the situation in question 4 so the program says something a person can act on and carries on with an empty list.
  2. A file holds one number per line. Read it, total the numbers, and print how many entries there were.
  3. A line is saved as Fifteen Dogs|14. Read the file and print each reminder as Fifteen Dogs — back in 14 days.
  4. Challenge. Why is FILE_NAME = "reminders.txt" at the top of a program better than writing "reminders.txt" in four places? Give two reasons, one of them about a shared drive.

Answers