Rocket built a notes program that saves one note to notes.txt. On Monday he saved a note about the fuel tank. On Tuesday he saved a note about the clock.
On Wednesday he opens notes.txt and finds only the clock note. "Where did Monday go?" he asks. "I saved it. I know I saved it."
Raven reads his code and points at one letter. "What do you notice?" she asks. "You open the file with w every time. We learned that w starts the file fresh."
Nova shows two pictures: a page being replaced, and a line being added to the bottom of a page. "Would you like a hint?" she asks. "There is a mode for adding. It is the letter a."
Rocket changes one letter and runs the program twice to be sure.
Mode "a" means append: add to the end. Everything already in the file stays. If the file does not exist yet, Python makes it.
Use "w" when you want to replace a file completely. Use "a" when you want to keep a growing record.
| Mode | Name | If the file exists | If it does not exist |
|---|---|---|---|
| "r" | read | reads it | FileNotFoundError |
| "w" | write | empties it first | creates it |
| "a" | append | adds to the end | creates it |
# add_note.py
note = input("Note to add: ")
with open("notes.txt", "a") as f:
f.write(note + "\n")
print("Note saved.")
print("Notes so far:")
with open("notes.txt") as f:
for line in f:
print("*", line.strip()) The first run:
Note to add: Fuel tank checked Note saved. Notes so far: * Fuel tank checked
The second run, the next day. The first note is still there:
Note to add: Clock tested Note saved. Notes so far: * Fuel tank checked * Clock tested
This program appends one line each time it runs, then counts the lines. The number grows by one with every run.
# visits.py
with open("visits.txt", "a") as f:
f.write("visit\n")
count = 0
with open("visits.txt") as f:
for line in f:
count = count + 1
print("Visits so far:", count) Visits so far: 3
| Mode | Does it keep the old lines? |
|---|---|
| "a" | ? |
| "w" | ? |
| "r" (it only reads) | ? |
Append mode turns a file into a growing record. Tomorrow you will build a dated log, a big step toward Mission Log.