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.
# 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.