PythonMastery
Python programs · Files · beginner

Append to a file in Python

Add new lines to the end of a file without deleting what is already there, using open() in 'a' (append) mode.

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

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.

Learn the idea: Files: Reading and Writing to Disk, File I/O, Pathlib, and Large Files