Python Docs
Python File Append — Full Cheat Sheet
What is File Appending?
Appending means adding new text to the end of a file without deleting the existing data. The "a" mode opens the file for appending.
Append Mode Properties
- a — Opens file for appending
- Does NOT erase existing content
- Writes at the end of the file only
- If file does not exist → creates a new file automatically
Basic Append Example
f = open("demofile.txt", "a")
f.write("This text is appended!")
f.close()Append a New Line
Use "\\n" to add a new line before writing.
with open("notes.txt", "a") as f:
f.write("\nNew line added.")Append Multiple Lines
Use writelines() to append a list of strings.
lines = [
"Line A" + "\n",
"Line B" + "\n"
]
with open("demo.txt", "a") as f:
f.writelines(lines)Append Can Create a File
Unlike "w" mode, append only adds to the file and will not erase anything. If the file is missing, Python creates it.
# If the file does not exist, "a" mode will create it
f = open("newfile.txt", "a")
f.write("Created automatically using append!")
f.close()Summary
- a: Append mode — adds to file
- a+: Append + read mode
- write(): writes text at end
- writelines(): writes list of strings
- with open(): best practice (auto-closes file)
- Append mode never deletes old data