The "w" mode is dangerous because it deletes everything.
What if we want to add a page to the book without burning the rest of it? We need the Archive mode (Append).
Appending to Files
"Append" means "add to the end". We use the "a" mode.
# "a" means "append mode"
file = open("list.txt", "a")
# \n creates a new line
file.write("\nBuy Milk")
file.close()
1
Create History
In file explorer, create archive.txt and type History 1: The Beginning.
2
Open to Append
In main.py, use open("archive.txt", "a"). Notice the "a"! Save it to file.
3
Add New History
Write the new_record variable to the file. Don't forget to close it.
Programmers use \n to mean "Press Enter" (New Line). If you don't use it, your text will be glued to the previous line!
Suggested SolutionExpandCollapse
ExpandCollapse
Solution:
# 1. Open to Append
file = open("archive.txt", "a")
# 2. Append new record with Newline
file.write(new_record)
# 3. Close
file.close()Advanced TipsWant more? Click to expandClick to collapse
F. Logs
- Appending is how "Log Files" (Diaries for servers) work.
- Servers write millions of lines to log files every day, always appending to the bottom, never deleting the past.
Loading...
Terminal
Terminal
Ready to run...