Back
+15 XP
Concept

Writing & Appending Files (`"w"` vs `"a"`)

`"w"` mode wipes existing file data to zero bytes immediately on open. `"a"` mode appends new text to the end without deleting past entries.

python
# Overwrite mode:
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("First entry\n")

# Append mode:
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Second entry\n")

# 16. Writing & Appending Files (`"w"` vs `"a"`) `"w"` mode wipes existing file data to zero bytes immediately on open. `"a"` mode appends new text to the end without deleting past entries: ```python # Overwrite mode: with open("log.txt", "w", encoding="utf-8") as f: f.write("First entry\n") # Append mode: with open("log.txt", "a", encoding="utf-8") as f: f.write("Second entry\n") ``` If you want write protection against accidentally destroying existing data, use `"x"` (exclusive creation mode). Opening an already-existing file with `"x"` immediately raises a `FileExistsError` instead of wiping it.

Checkpoint

What happens to existing file contents when you open a file with `open(path, 'w')`?

Practice

Write `"Alpha"` using `"w"` mode to `test_mode.txt`. Then append `"Beta"` using `"a"` mode. Read the file and print its contents.

Terminal
01
Tap code blocks below to assemble
Available Blocks