Nearby lessons

90 of 159

Python - Append Files

📌 What You Will Learn
  • Open a file in append mode using the a mode character
  • Understand that append mode never overwrites existing data
  • Append new data at the end of an existing file
  • Compare append mode with write mode
  • Know the difference between a and a+ modes

The Append Mode

The a mode opens an existing file for appending data.

Appending means adding new data at the end of the file while keeping the existing content unchanged.

Features of Append Mode

  • Existing data is not overwritten.
  • New data is added at the end of the file.
  • If the file does not exist, Python creates a new file.

Syntax

🐍Code Cell
1f = open(filename, "a")
Output
No output captured.

Example: Append Data to a File

Assume that abcd.txt already contains the following data:

Durga
Software
Solutions

Program

🐍Code Cell
1f = open("abcd.txt", "a")
2 
3f.write("JAVA\n")
4f.write("PYTHON\n")
5 
6print("Data appended to the file successfully")
7 
8f.close()
Output
Data appended to the file successfully

Contents of abcd.txt After Appending

This output assumes abcd.txt already existed with the original three lines before the append program ran. The in-browser editor does not create that file, so running the program there will produce a file containing only JAVA and PYTHON.

Durga
Software
Solutions
JAVA
PYTHON

Explanation

When the file is opened in a mode, the file pointer moves to the end of the file.

The new strings JAVA and PYTHON are added after the existing content, and the original three lines are preserved.

Append Mode vs Write Mode

Append Mode (a) Write Mode (w)
Preserves existing data. Overwrites existing data.
Adds new data at the end of the file. Replaces the whole file content.
Creates a new file if it does not exist. Creates a new file if it does not exist.
Used for logs, records, and incremental data. Used when the file should start fresh.

The a+ Mode

In addition to appending, the a+ mode also allows us to read data from the file.

Like a, it never overwrites existing data.

🐍Code Cell
1f = open("abcd.txt", "a+")
Output
No output captured.

When to Use Append Mode

  • Adding new records to an existing file.
  • Writing log entries where older entries must be preserved.
  • Building a file gradually across multiple runs of a program.
📝 Key Takeaways
  • The a mode opens a file and adds new data at the end
  • Append mode preserves all existing content - nothing is overwritten
  • If the file does not exist, append mode creates a new file
  • w mode overwrites existing data, while a mode never does
  • a+ mode appends data and also allows reading

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6