How to open a file in append mode with Python?

File handling in Python includes opening files in append mode, which allows you to add new content without overwriting existing data. This article explores different methods to open files in append mode with practical examples.

Basic Append Mode ('a')

The simplest way to open a file in append mode is using the 'a' mode parameter. This opens the file for writing and positions the cursor at the end of the file.

# Open file in append mode and write text
file = open('myfile.txt', 'a')
file.write("This is appended text.\n")
file.close()

print("Text appended successfully!")
Text appended successfully!

Using Context Managers (Recommended)

Context managers automatically handle file closing and are the preferred method for file operations. They ensure proper resource management even if errors occur.

# Using 'with' statement for automatic file closing
with open('myfile.txt', 'a') as file:
    file.write("Line 1 appended\n")
    file.write("Line 2 appended\n")

print("Lines appended using context manager!")
Lines appended using context manager!

Append Mode with Reading ('a+')

Use 'a+' mode to both read existing content and append new data. Note that the file pointer starts at the end, so you need to seek to the beginning to read existing content.

# Create a sample file first
with open('sample.txt', 'w') as f:
    f.write("Original content\n")

# Open in a+ mode for reading and appending
with open('sample.txt', 'a+') as file:
    # Move to beginning to read existing content
    file.seek(0)
    existing_content = file.read()
    print("Existing content:", existing_content.strip())
    
    # Append new content
    file.write("New appended line\n")
Existing content: Original content

Binary Append Mode ('ab')

For binary files, use 'ab' mode to append binary data without corrupting the file format.

# Append binary data to a file
binary_data = b"Binary content to append"

with open('data.bin', 'ab') as file:
    file.write(binary_data)

print("Binary data appended successfully!")
Binary data appended successfully!

Practical Example: Log File

A common use case is appending entries to log files. Here's a practical example:

import datetime

def log_message(message):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open('app.log', 'a') as log_file:
        log_file.write(f"[{timestamp}] {message}\n")

# Add log entries
log_message("Application started")
log_message("User logged in")
log_message("Data processed successfully")

print("Log entries added!")
Log entries added!

Comparison of Append Modes

Mode Description Reading Writing
'a' Append text No Yes (at end)
'a+' Append and read text Yes Yes (at end)
'ab' Append binary No Yes (at end)
'ab+' Append and read binary Yes Yes (at end)

Conclusion

Use append mode ('a') to add content without overwriting existing data. Always prefer context managers with the 'with' statement for automatic file closing and better resource management. Choose the appropriate mode based on whether you need reading capabilities and binary or text data handling.

Updated on: 2026-03-24T17:20:19+05:30

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements