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.
'a'
): Opens the file for writing; content is added at the end. Creates the file if it doesn't exist.'a+'
): Opens the file for both appending and reading.'w'
), append mode does not erase the existing content.seek()
if reading is required before writing (in 'a+'
mode).with open('log.txt', 'a') as file:
file.write('New log entry\\n')
lines = ['Line 1\\n', 'Line 2\\n']
with open('notes.txt', 'a') as file:
file.writelines(lines)
with open('data.txt', 'a') as file:
for i in range(3):
file.write(f'Item {i}\\n')
text = input("Enter your note: ")
with open('notes.txt', 'a') as file:
file.write(text + '\\n')
with open('newfile.txt', 'a') as file:
file.write('First line in a new file\\n')
with open('combined.txt', 'a+') as file:
file.seek(0)
print("Current content:\\n", file.read())
file.write('Appended after reading\\n')
from datetime import datetime
with open('timelog.txt', 'a') as file:
file.write(f"{datetime.now()}: Task done\\n")
name, score = 'John', 95
with open('scores.csv', 'a') as file:
file.write(f'{name},{score}\\n')
try:
result = 10 / 0
except ZeroDivisionError as e:
with open('errors.log', 'a') as file:
file.write(f"Error: {e}\\n")
with open('summary.txt', 'a') as file:
file.write('\\n') # Adds a blank line