Python Append File

Introduction

Appending to files in Python is a common task for many applications, such as logging data, adding new entries, or updating records. Python provides simple methods to append data to the end of a file without overwriting its existing content. You can use the open() function with the append mode ('a') to achieve this.

Opening a File for Appending

To append data to a file in Python, you need to open it in append mode ('a'). The open() function is used to open the file, and the file object allows you to write data to it.

Syntax

file = open('file_name.txt', 'a')

Example

Let’s say you have a file named example.txt and you want to append some data to it.

import os

# Appending data to the file
try:
    with open('example.txt', 'a') as file:
        file.write('This line is appended.\n')
    print("Data appended successfully.")
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Data appended successfully.

Using the with Statement

The with statement is commonly used for file handling because it ensures that the file is properly closed after its suite finishes, even if an exception is raised. This makes the code more concise and reduces the risk of leaving files open.

Example

# Using with statement to append to a file
try:
    with open('example.txt', 'a') as file:
        file.write('Appending another line using with statement.\n')
    print("Data appended successfully.")
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Data appended successfully.

Appending Multiple Lines

You can append multiple lines to a file by writing them one by one or by using the writelines() method.

Example: Writing Lines One by One

# Appending multiple lines one by one
lines = ['First appended line\n', 'Second appended line\n', 'Third appended line\n']
try:
    with open('example.txt', 'a') as file:
        for line in lines:
            file.write(line)
    print("Multiple lines appended successfully.")
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Example: Using writelines()

# Appending multiple lines using writelines()
lines = ['Fourth appended line\n', 'Fifth appended line\n']
try:
    with open('example.txt', 'a') as file:
        file.writelines(lines)
    print("Multiple lines appended successfully.")
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Multiple lines appended successfully.

Handling File Exceptions

It’s a good practice to handle exceptions that may occur during file operations to ensure your program can respond to errors appropriately.

Example

try:
    with open('example.txt', 'a') as file:
        file.write('Appending with exception handling.\n')
except FileNotFoundError:
    print("The file does not exist.")
except PermissionError:
    print("Permission denied.")
except Exception as e:
    print(f"An error occurred: {e}")

Output

Data appended successfully.

Real-World Example: Appending Log Messages

Let’s create a simple logging function that appends log messages to a file.

Example

def log_message(message, filename='log.txt'):
    try:
        with open(filename, 'a') as file:
            file.write(message + '\n')
        print("Log message appended successfully.")
    except FileNotFoundError:
        print(f"The file '{filename}' does not exist.")
    except PermissionError:
        print("Permission denied.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Appending log messages
log_message('This is an info message.')
log_message('This is a warning message.')
log_message('This is an error message.')

Output

Log message appended successfully.
Log message appended successfully.
Log message appended successfully.

Contents of log.txt

This is an info message.
This is a warning message.
This is an error message.

Conclusion

Appending to files in Python is straightforward and efficient, allowing you to add new data to the end of a file without overwriting its existing content. By using the with statement, you can ensure that files are properly closed after their suite finishes, making your code more robust and concise. Understanding file appending operations is essential for tasks like data logging, updating records, and maintaining logs in Python applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top