Question

How to Append to a File in Python Instead of Overwriting It

pythonfileappend

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.

Take Quiz

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 mode
  • with ensures the file is closed automatically
  • file.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", "Second message\n", "Third message\n"]

with open("messages.txt", "a") as file:
    file.writelines(lines)

Append and read mode

If you want to both append and read, use 'a+':

with open("notes.txt", "a+") as file:
    file.write("Another note\n")

This is less common for beginners, but useful when you need both behaviors in the same file handle.

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

  1. Python evaluates open("journal.txt", "a").
  2. If journal.txt does not exist, Python creates it.
  3. If it already exists, Python keeps its current contents.
  4. The file cursor is positioned at the end of the file.
  5. file.write("Day 1: Started learning Python\n") adds the new text after the existing content.
  6. The with block finishes.
  7. 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

This shows that append mode keeps adding content to the end each time.

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.

Take Quiz

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:
        return

    with open("scores.txt", "a") as file:
        file.write(f"{score}\n")

Structured appending

In real codebases, developers often format appended data consistently:

from datetime import datetime

with open("events.log", "a") as file:
    file.write(f"[{datetime.now()}] Server started\n")

Error handling

Sometimes file operations are wrapped in try/except blocks.

try:
    with open("output.txt", "a") as file:
        file.write("Saved successfully\n")
except OSError as error:
    print("Could not write to file:", error)

This helps programs fail gracefully if the file cannot be accessed.

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:

with open("data.txt", "a") as file:
    file.write("First line\n")
    file.write("Second line\n")

Not using with

Less safe code:

file = open("data.txt", "a")
file.write("Hello\n")
file.close()

Problem:

  • If an error happens before close(), the file may stay open longer than intended.

Better:

with open("data.txt", "a") as file:
    file.write("Hello\n")

Expecting append mode to insert text in the middle

Append mode always writes at the end. It does not insert content at an arbitrary position.

Assuming the file must already exist

Append mode creates the file if it does not already exist. This is often useful, but beginners sometimes do not realize it.

Comparisons

ModeMeaningIf file existsIf file does not existCommon use
'w'WriteOverwrites contentsCreates fileStart fresh
'a'AppendAdds to endCreates fileKeep old data
'r'ReadReads onlyErrorView contents
'a+'Append and readAdds to end and allows readingCreates fileRead and then append

'w' vs 'a'

  • Use 'w' when you want to replace the whole file.
  • Use 'a' when you want to preserve old content.

write() vs writelines()

MethodPurposeNotes
write()Writes one stringYou control newlines manually
writelines()Writes multiple stringsDoes not add newlines automatically

with open(...) vs manual open/close

ApproachAdvantage
with open(...)Automatically closes the file
open() and close() manuallyMore error-prone for beginners
Take Quiz

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 \n yourself 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", "two\n"]
with open("data.txt", "a") as file:
    file.writelines(lines)

Easy mistake to remember

  • 'w' = wipe and write
  • 'a' = add to the end

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?

Yes. It automatically closes the file and is the recommended style in Python.

Take Quiz

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

  1. Ask the user to enter a task.
  2. Append the task to a file named tasks.txt.
  3. Store each task on its own line.
  4. Do not overwrite existing tasks.
  5. Print a confirmation message after saving.
Take Quiz

Keep learning

Related questions

View more