Append Files
Python · File Handling
Theory
Mode 'a' (append) opens a file for writing but keeps everything already in it: every write goes to the end of the file. If the file does not exist yet, it is created, just like 'w'. The difference is that 'w' starts from an empty file each time, while 'a' adds on.
This makes append the natural choice for logs and audit trails. Each run of with open('log.txt', 'a') as f: f.write('Login Ravi\n') adds one new line after the previous ones, so the history builds up over time. As with write mode, you must add '\n' yourself or entries will run together on one line. In append mode the write position is always the end, even if you move it with seek(); 'a+' also lets you read the file.
Why we use it
Some files must grow rather than be replaced - activity logs, daily records, error histories. Append mode adds new entries safely without having to read and rewrite the whole file.
When to use it
Use 'a' to add records to a log or running file. Use 'w' when each run should produce a fresh file. For high-volume logging, Python's logging module handles formatting and file rotation for you.
How it works
- open('log.txt', 'a')
- Does log.txt exist? Yes: Keep existing lines, position at the end. No: Create an empty file.
- f.write('Login Ravi\n')
- New text lands after the old content
- Close: file now has one more line
Syntax
with open('file.txt', 'a') as f:
f.write(text)Example
with open('log.txt', 'a') as f:
f.write('New entry\n')Key points
- Creates the file if it doesn't already exist
- Useful for logging where history should be preserved
- Writes always go to the end of the file
- Remember to add '\n' at the end of each entry
- 'a+' allows reading as well as appending