Python Append Mode
Table of Contents
In the last lesson, we learned about Python Writing Files. After learning how to write files, let us learn about append mode in Python. Writing erases the file. Appending adds to the end. That is the difference.
In this tutorial, we will learn how to use append mode to add data to an existing file without erasing the old content.
What Is Append Mode in Python?
Append mode is a file mode that lets us add new content to the end of an existing file. It does not erase the old content. It just adds to it.
It is like adding a new page to a notebook. We do not tear out the old pages. We just write on the next blank page.
How to Open a File in Append Mode in Python
To append to a file, we open it in append mode. We use "a".
file = open("output.txt", "a")Now file is a file object. We can use it to write.
If the file does not exist, Python creates it. If it exists, Python opens it and moves the cursor to the end.
How to Append to a File with write()
The write() method works the same way. It writes a string to the file. But in append mode, it writes to the end.
with open("output.txt", "a") as file: file.write("This is a new line.\n")If output.txt already contained:
Hello, world!After running this, it will contain:
Hello, world!This is a new line.The old content is still there. The new content was added to the end.
How to Append Multiple Lines to a File in Python
We can append multiple lines by calling write() multiple times.
with open("log.txt", "a") as file: file.write("Line 1\n") file.write("Line 2\n") file.write("Line 3\n")Each time we run this, the lines are added to the end of the file.
Python Append to File Example β Logging
Logging is the most common use of append mode. We want to keep a record of what happened. And we want to add to it each time.
import datetime
def log_message(message): timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open("log.txt", "a") as file: file.write(f"{timestamp} - {message}\n")
log_message("Program started")log_message("User logged in")log_message("Program ended")If we run this program twice, log.txt will contain:
2025-01-15 10:00:00 - Program started2025-01-15 10:00:00 - User logged in2025-01-15 10:00:00 - Program ended2025-01-15 10:00:01 - Program started2025-01-15 10:00:01 - User logged in2025-01-15 10:00:01 - Program endedEach run adds new lines. The old lines are not erased.
Another Example β Tracking Scores with Append Mode
def save_score(player, score): with open("scores.txt", "a") as file: file.write(f"{player}: {score}\n")
save_score("Alex", 85)save_score("Sam", 92)save_score("John", 78)The file scores.txt will contain:
Alex: 85Sam: 92John: 78If we add more scores later, they will be added to the end.
Append Mode vs Write Mode in Python
Let me make the difference clear.
Write mode "w":
- Erases the file if it exists
- Creates a new file if it does not
- Starts writing from the beginning
Append mode "a":
- Keeps the existing content
- Creates a new file if it does not exist
- Adds new content to the end
So if we want to keep old data and add new data, use append mode.
Common Mistakes with Append Mode in Python
Mistake 1: Using write mode when we meant append
with open("data.txt", "w") as file: file.write("New data")This erases the file. If we wanted to add to the end, we use "a".
Mistake 2: Forgetting the newline character
with open("log.txt", "a") as file: file.write("New message")If we run this multiple times, the messages will be on the same line:
New messageNew messageNew messageFix: Add \n.
file.write("New message\n")Mistake 3: Opening in append mode but expecting read
with open("data.txt", "a") as file: content = file.read()This gives an error. Because append mode is for writing. It does not support reading.
Fix: Open in read mode if you want to read.
with open("data.txt", "r") as file: content = file.read()Or use "a+" for both append and read.
with open("data.txt", "a+") as file: file.write("New data\n") file.seek(0) content = file.read()A Complete Example β Simple To-Do List with Append Mode
Letβs build a simple to-do list that saves tasks to a file.
def add_task(task): with open("todos.txt", "a") as file: file.write(f"{task}\n") print(f"Task added: {task}")
def show_tasks(): try: with open("todos.txt", "r") as file: tasks = file.readlines() if tasks: print("\nYour tasks:") for i, task in enumerate(tasks, 1): print(f"{i}. {task.strip()}") else: print("No tasks yet") except FileNotFoundError: print("No tasks yet")
add_task("Buy groceries")add_task("Call mom")show_tasks()Output
Task added: Buy groceriesTask added: Call mom
Your tasks:1. Buy groceries2. Call momIf we run the program again and add more tasks, they will be appended to the same file.
Next, we will learn Python Working with CSV Files, where file handling becomes useful for table-like data such as names, ages, and marks.