How to Append to a File in Python: Simple Guide
To append to a file in Python, open the file using
open('filename', 'a') mode, then write your content with write(). This mode adds new data to the end without deleting existing content.Syntax
Use open(filename, 'a') to open a file for appending. The 'a' mode means new data is added at the end of the file. Use write() to add text.
- filename: the file path as a string
- 'a': append mode
- write(): method to add text
python
file = open('example.txt', 'a') file.write('New text to add\n') file.close()
Example
This example opens a file named log.txt in append mode and adds a new line of text. If the file does not exist, it will be created automatically.
python
with open('log.txt', 'a') as file: file.write('Appended line\n') print('Text appended successfully.')
Output
Text appended successfully.
Common Pitfalls
One common mistake is opening the file in write mode 'w', which erases existing content instead of appending. Also, forgetting to add a newline \n can cause text to run together.
python
wrong = "with open('file.txt', 'w') as f:\n f.write('This overwrites the file\n')" right = "with open('file.txt', 'a') as f:\n f.write('This adds to the file\n')"
Quick Reference
| Mode | Description |
|---|---|
| 'r' | Read only (file must exist) |
| 'w' | Write only (overwrites file or creates new) |
| 'a' | Append only (adds to end or creates new) |
| 'r+' | Read and write (file must exist) |
| 'a+' | Read and append (creates new if missing) |
Key Takeaways
Use 'a' mode in open() to append without deleting existing content.
Always close the file or use 'with' to handle files safely.
Add '\n' to write() calls to keep lines separate.
Opening in 'w' mode will erase the file, not append.
If the file doesn't exist, 'a' mode creates it automatically.