Question
I want to write data to a file without deleting its existing contents. How can I append to a file instead of overwriting it?
For example, I want new text to be added to the end of the file each time my program runs, rather than replacing what is already there.
Short Answer
By the end of this page, you will understand how file append mode works in Python, how it differs from write mode, how to safely add new content to an existing file, and what common mistakes to avoid when working with files.
Concept
In Python, writing to a file depends on the file mode you choose when opening it.
If you open a file with:
'w'— Python writes to the file and overwrites existing content.'a'— Python appends to the file, meaning new content is added to the end.
Appending matters when you want to preserve existing data, such as:
- log files
- user activity history
- saved notes
- reports generated over time
A common beginner mistake is using write mode ('w') when they actually want to keep old content. Write mode starts fresh, while append mode keeps what is already there and adds new data after it.
In real programming, choosing the correct file mode is important because files often store information collected over time. Using the wrong mode can accidentally erase valuable data.
Mental Model
Think of a file like a notebook.
- Opening a file with
'w'is like tearing out all previous pages and starting over. - Opening a file with
'a'is like turning to the last page and writing more.
So if you want to keep everything already written, use append mode.
Syntax and Examples
The basic syntax is:
with open("example.txt", "a") as file:
file.write("New line of text\n")
What this does
open("example.txt", "a")opens the file in append modewithensures the file is closed automaticallyfile.write(...)adds text to the end of the file
Example
with open("log.txt", "a") as file:
file.write("Program started\n")
If log.txt already contains:
Previous run
After running the code, it becomes:
Previous run
Program started
Appending multiple lines
lines = ["First message\n", , ]
(, ) file:
file.writelines(lines)
Step by Step Execution
Consider this code:
with open("journal.txt", "a") as file:
file.write("Day 1: Started learning Python\n")
Step by step
- Python evaluates
open("journal.txt", "a"). - If
journal.txtdoes not exist, Python creates it. - If it already exists, Python keeps its current contents.
- The file cursor is positioned at the end of the file.
file.write("Day 1: Started learning Python\n")adds the new text after the existing content.- The
withblock finishes. - Python automatically closes the file.
Example trace
Suppose journal.txt initially contains:
Day 0: Installed Python
After the code runs, it contains:
Day 0: Installed Python
Day 1: Started learning Python
If you run the same code again, the new line is appended again:
Day 0: Installed Python
Day 1: Started learning Python
Day 1: Started learning Python
Real World Use Cases
Appending to files is common in many practical situations.
Logging
with open("app.log", "a") as file:
file.write("User logged in\n")
Applications often append events to log files instead of replacing them.
Saving user actions
with open("history.txt", "a") as file:
file.write("Searched for: python file modes\n")
This preserves a history of actions over time.
Storing generated reports
A script that runs every day might append a summary line to a report file.
Exporting collected data
If a script gathers data from an API every hour, appending lets it keep previous results while adding new ones.
Simple audit trails
Programs may append important actions such as account changes, file uploads, or errors for later review.
Real Codebase Usage
In real projects, developers often use append mode as part of larger patterns.
Logging and diagnostics
Appending is frequently used for logs, especially in simple scripts and command-line tools.
def log_message(message):
with open("app.log", "a") as file:
file.write(message + "\n")
Validation before writing
Developers often validate data before appending it.
def save_username(username):
if not username:
return
with open("users.txt", "a") as file:
file.write(username + "\n")
This uses a guard clause to skip invalid input.
Early return for bad data
def save_score(score):
if score < 0:
(, ) file:
file.write()
Common Mistakes
Here are common mistakes beginners make when appending to files.
Using 'w' instead of 'a'
Broken code:
with open("data.txt", "w") as file:
file.write("New value\n")
Problem:
- This overwrites the file.
Fix:
with open("data.txt", "a") as file:
file.write("New value\n")
Forgetting a newline
Broken code:
with open("data.txt", "a") as file:
file.write("First line")
file.write("Second line")
Result:
First lineSecond line
Fix:
Comparisons
| Mode | Meaning | If file exists | If file does not exist | Common use |
|---|---|---|---|---|
'w' | Write | Overwrites contents | Creates file | Start fresh |
'a' | Append | Adds to end | Creates file | Keep old data |
'r' | Read | Reads only | Error | View contents |
'a+' | Append and read | Adds to end and allows reading | Creates file | Read and then append |
Cheat Sheet
# Append text to a file
with open("file.txt", "a") as file:
file.write("Hello\n")
File modes
'r'→ read only'w'→ write and overwrite'a'→ append to end'a+'→ append and read
Key rules
- Append mode keeps existing content.
- Append mode creates the file if needed.
write()expects a string.- Add
\nyourself if you want a new line. - Prefer
with open(...)so the file closes automatically.
Useful examples
with open("log.txt", "a") as file:
file.write("App started\n")
lines = ["one\n", ]
(, ) file:
file.writelines(lines)
FAQ
How do I append to a file in Python?
Open the file with mode 'a' and use write() or writelines().
with open("file.txt", "a") as file:
file.write("More text\n")
Does append mode create the file if it does not exist?
Yes. If the file does not exist, Python creates it.
What is the difference between 'w' and 'a' in Python?
'w' overwrites the file. 'a' keeps existing content and adds new content at the end.
Why is my appended text appearing on the same line?
Because write() does not add a newline automatically. Add \n yourself.
Can I read and append to the same file?
Yes. Use 'a+' if you need both reading and appending.
Should I use with open() when appending to a file?
Mini Project
Description
Build a small Python script that stores a running list of tasks in a text file. Each time the program runs, it should append a new task instead of deleting the previous ones. This demonstrates how append mode is used in simple persistent storage.
Goal
Create a script that adds new task entries to a file while preserving all existing tasks.
Requirements
- Ask the user to enter a task.
- Append the task to a file named
tasks.txt. - Store each task on its own line.
- Do not overwrite existing tasks.
- Print a confirmation message after saving.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.