0
0
Pythonprogramming~5 mins

Appending data to files in Python

Choose your learning style9 modes available
Introduction

Appending data to files lets you add new information without deleting what is already there. It helps keep old data safe while adding fresh content.

Saving new messages to a chat history without losing old messages
Adding new entries to a log file to track events over time
Recording scores in a game without erasing previous scores
Keeping a list of tasks updated by adding new tasks at the end
Syntax
Python
with open('filename.txt', 'a') as file:
    file.write('Your new data\n')

The 'a' mode opens the file for appending, so new data goes at the end.

Use \n to add a new line if you want each entry on its own line.

Examples
This adds a reminder to the end of the notes.txt file on a new line.
Python
with open('notes.txt', 'a') as file:
    file.write('Remember to buy milk\n')
This appends a login event to the log.txt file.
Python
with open('log.txt', 'a') as file:
    file.write('User logged in at 10:00 AM\n')
This adds a new row to a CSV file without removing existing rows.
Python
with open('data.csv', 'a') as file:
    file.write('4,John,25\n')
Sample Program

This program adds three lines to 'example.txt'. Then it reads the whole file and prints it so you can see all the lines including the new ones.

Python
filename = 'example.txt'

# Append three lines to the file
with open(filename, 'a') as file:
    file.write('First line\n')
    file.write('Second line\n')
    file.write('Third line\n')

# Read and print the file content to see the result
with open(filename, 'r') as file:
    content = file.read()
    print(content)
OutputSuccess
Important Notes

If the file does not exist, opening with 'a' mode will create it automatically.

Appending does not erase existing content, so be careful not to add duplicate or unwanted data.

Summary

Use 'a' mode to open files for appending data at the end.

Remember to add '\n' if you want new lines for each entry.

Appending keeps old data safe and adds new data after it.