Appending Files
In this tutorial, we'll add new content to the end of an existing file.
Appending means adding new content to the end of a file.
Use "a" mode:
with open("log.txt", "a") as file:
file.write("Program started\n")
If log.txt already has content, the new line is added after it. If the file does not exist, Python creates it.
Append vs Write
Write mode replaces:
open("log.txt", "w")
Append mode keeps old content:
open("log.txt", "a")
Use append mode for logs, journals, score history, or anything that grows over time.
Example: Simple Journal
entry = input("Journal entry: ")
with open("journal.txt", "a") as file:
file.write(entry + "\n")
Each time the program runs, it adds another line.
Newline Reminder
Append mode does not add newlines automatically. If you want each entry on its own line, include \n.
Reading Back Appended Content
After appending, you can read the file to check what happened:
with open("journal.txt", "r") as file:
print(file.read())
This is a good habit while learning file handling. Write or append a small amount, then read the file back to confirm it looks right.
Common Use Case: Logs
Append mode is commonly used for logs because logs grow over time:
with open("events.txt", "a") as file:
file.write("User logged in\n")
Each event is added without deleting the older events.
Practice
Create a program that asks for a task and appends it to tasks.txt.