CodingNic

Files, Errors, and Automation

Append Mode

Files, Errors, and Automation 20 min read

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.

python
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.

python
with open("notes.txt", "a") as file:
    file.write("New Text")

Example File Before Append

text
Learn Python
Practice Daily

Add New Line

python
with open("notes.txt", "a") as file:
    file.write("\nKeep Going")

File After Append

text
Learn Python
Practice Daily
Keep Going

Appending User Input

python
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

python
with open("tasks.txt", "a") as file:
    for task in ["Study", "Code", "Build"]:
        file.write(task + "\n")

File Content

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

text
Tom
Sara

Then run again and add:

text
Ali

Final file:

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

text
Tom
Sara
Ali

Real World Use Case

Programs use append mode for logs, journals, attendance lists, chat history, and reports.

Quiz

  1. What does "a" mean?
  2. Does append mode delete old content?
  3. Why use \n when appending?
  4. 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.