Append Mode
Append Mode
Sometimes you want to add new text to a file without deleting the old content.
This is where append mode is useful.
What Is Append Mode?
Append mode uses "a" when opening a file.
It means:
- Keep existing content
- Add new content at the end
Why Append Mode Matters
Many real programs need to keep adding data:
- Journal entries
- Logs
- Usernames
- Notes
- Reports
Write Mode vs Append Mode
Write Mode "w"
Replaces old content.
with open("notes.txt", "w") as file:
file.write("New Text")
Old content is erased.
Append Mode "a"
Keeps old content and adds new text.
with open("notes.txt", "a") as file:
file.write("New Text")
Example File Before Append
Learn Python
Practice Daily
Add New Line
with open("notes.txt", "a") as file:
file.write("\nKeep Going")
File After Append
Learn Python
Practice Daily
Keep Going
Appending User Input
note = input("Enter note: ")
with open("journal.txt", "a") as file:
file.write(note + "\n")
Each run adds a new note.
Add Many Lines with a Loop
with open("tasks.txt", "a") as file:
for task in ["Study", "Code", "Build"]:
file.write(task + "\n")
File Content
Study
Code
Build
Common Beginner Errors
Forgetting \n
New text may join the last line.
Using "w" by Mistake
This removes old content.
Wrong File Name
Check spelling carefully.
Code Along
Create names.txt.
Add:
Tom
Sara
Then run again and add:
Ali
Final file:
Tom
Sara
Ali
Mini Challenge
Build a guest list saver.
Steps:
- Ask the user to enter a name
- Save the name into
guests.txt - Add a new line
- Run again to keep adding more names
Example file:
Tom
Sara
Ali
Real World Use Case
Programs use append mode for logs, journals, attendance lists, chat history, and reports.
Quiz
- What does
"a"mean? - Does append mode delete old content?
- Why use
\nwhen appending? - What happens if you use
"w"instead?
Assignment
Create a program that asks for 3 goals and saves them into goals.txt using append mode.
Summary
You learned that append mode keeps old file content and adds new text to the end of a file.