Appending to Files in Python

Appending to files is a common task in Python when you want to add content without overwriting existing data. Python provides an 'a' mode in the open() function to simplify this process.

Key Concepts

10 Python Examples for Appending to Files

Example 1: Basic append using 'a' mode

with open('log.txt', 'a') as file:
    file.write('New log entry\\n')

Example 2: Appending multiple lines

lines = ['Line 1\\n', 'Line 2\\n']
with open('notes.txt', 'a') as file:
    file.writelines(lines)

Example 3: Appending inside a loop

with open('data.txt', 'a') as file:
    for i in range(3):
        file.write(f'Item {i}\\n')

Example 4: Appending user input

text = input("Enter your note: ")
with open('notes.txt', 'a') as file:
    file.write(text + '\\n')

Example 5: Creating a file if it doesn't exist

with open('newfile.txt', 'a') as file:
    file.write('First line in a new file\\n')

Example 6: Using 'a+' to read and append

with open('combined.txt', 'a+') as file:
    file.seek(0)
    print("Current content:\\n", file.read())
    file.write('Appended after reading\\n')

Example 7: Append with a timestamp

from datetime import datetime

with open('timelog.txt', 'a') as file:
    file.write(f"{datetime.now()}: Task done\\n")

Example 8: Append structured data (CSV-style)

name, score = 'John', 95
with open('scores.csv', 'a') as file:
    file.write(f'{name},{score}\\n')

Example 9: Append error logs in exception handling

try:
    result = 10 / 0
except ZeroDivisionError as e:
    with open('errors.log', 'a') as file:
        file.write(f"Error: {e}\\n")

Example 10: Append a blank line for separation

with open('summary.txt', 'a') as file:
    file.write('\\n')  # Adds a blank line