Append mode ("a") adds new text to the end of a file. The text that is already in the file stays. This is the mode for logs, diaries and any file that grows over time.
The program
python
# start with a file that has two lines with open("log.txt", "w", encoding="utf-8") as f: f.write("Ada logged in\n") f.write("Ada saved a file\n") # later: add one more line to the end with open("log.txt", "a", encoding="utf-8") as f: f.write("Ada logged out\n") with open("log.txt", encoding="utf-8") as f: print(f.read(), end="")
output
Ada logged in Ada saved a file Ada logged out
How it works
"w"and"a"both create the file if it does not exist. The difference is what happens when it does exist:"w"empties it first, and"a"keeps the contents and writes after them.- In append mode, every write goes to the end of the file. You cannot use it to insert a line in the middle.
- As with
"w", you add the\nyourself. If the last line of the file has no\n, the new text joins that line.
The difference between "w" and "a"
This program runs the same write three times in each mode:
python
for mode in ["w", "a"]: with open("demo.txt", "w", encoding="utf-8"): pass # start each test with an empty file for visit in range(3): with open("demo.txt", mode, encoding="utf-8") as f: f.write(f"visit {visit + 1}\n") with open("demo.txt", encoding="utf-8") as f: print(f"mode {mode!r}:", f.read().split("\n")[:-1])
output
mode 'w': ['visit 3'] mode 'a': ['visit 1', 'visit 2', 'visit 3']
With "w", each open deleted the previous line, so only the last visit is left.
Related programs: Write to a file.