Topic 02

Writing Without Destroying

Hands-on

Writing a file is as easy as reading one, and far more dangerous. Open a file for writing in the usual mode and its old contents are gone before you have written a single character. This page shows the difference between replacing a file and adding to it, the one-letter slip that quietly erases a log, and the careful way to replace a file that matters.

Think of the difference between writing on a fresh page and adding a line at the bottom of a diary. Replacing a file is tearing out the old page first. Sometimes that is what you want; you should never do it by accident.

"w": Replace

The second argument to open is the mode. The letter w means write, and it empties the file the moment it is opened, or creates the file if it does not exist yet. Then write puts text into it. write adds exactly what you give it and nothing more, so each line needs its own line break, written as backslash-n inside the string.

write.py
with open("shopping.txt", "w", encoding="utf-8") as f:
    f.write("bread\n")
    f.write("milk\n")

with open("shopping.txt", encoding="utf-8") as f:
    print(f.read())
Output
bread
milk

"a": Append

The letter a means append. The file keeps what it already has, and new text goes at the end. It is the right mode for anything that accumulates: a log, a diary, a record of payments.

The Mistake That Erases a Log

Here is the mistake to recognise. A small program keeps a daily log. Each day it opens the log and writes one line. The program below imitates three days with a loop. Opened with w, each day's opening empties the file, and at the end only Wednesday's line survives. Nothing warned anyone.

log_wrong.py
for day in ["Monday", "Tuesday", "Wednesday"]:
    with open("log.txt", "w", encoding="utf-8") as f:
        f.write(f"{day}: backed up the photos\n")

with open("log.txt", encoding="utf-8") as f:
    print(f.read())
Output
Wednesday: backed up the photos

The fixed version differs by one letter, a instead of w, and writes to a fresh file, log2.txt, so the result is not mixed up with the first experiment. All three days are kept.

log.py
for day in ["Monday", "Tuesday", "Wednesday"]:
    with open("log2.txt", "a", encoding="utf-8") as f:
        f.write(f"{day}: backed up the photos\n")

with open("log2.txt", encoding="utf-8") as f:
    print(f.read())
Output
Monday: backed up the photos
Tuesday: backed up the photos
Wednesday: backed up the photos

Replacing Safely

Sometimes you really do want to replace a file: a report rebuilt from scratch, a settings file saved with new values. The risk is the moment in between. If the program crashes after w has emptied the file but before the new content is written, the old content is gone and the new content never arrived.

The careful pattern is to write the new version to a separate file first and, only once it is complete, swap it into place. The pathlib module, which the next topic introduces properly, has a replace method that does the swap in one step: the finished file takes the old one's name. If the program fails while writing, the original is still whole.

safe_save.py
from pathlib import Path

report = "Total spent: 177.75\nFood: 58.50\n"

new_file = Path("report.txt.new")
new_file.write_text(report, encoding="utf-8")
new_file.replace("report.txt")

print(Path("report.txt").read_text(encoding="utf-8"))
Output
Total spent: 177.75
Food: 58.50

write_text and read_text are shortcuts that open, write or read, and close a file in one call. They are handy when you want the whole file at once.

One letter, two very different results
Mode "w"
Yesterday's lines are gone; only today's remain.
Mode "a"
Yesterday's lines, then today's, in order.
Common Confusions
  • "Mode w adds to the file." It empties the file the moment it is opened. Use a to add to the end.
  • "write adds a new line by itself." It writes exactly the text you give it. Add the line break yourself with backslash-n.
  • "Replacing a file in place is fine if the program is simple." A crash at the wrong moment still loses the old version. Write a new file first, then swap it in.
Why It Matters
  • Overwriting data by accident is the most painful beginner mistake with files. After this page it is a choice you make on purpose.
  • Write-then-swap is how careful software saves anything that matters, from documents to databases.

Knowledge Check

What happens to a file's existing contents when you open it with mode "w"?

  • They are kept, and new text goes after them
  • They are erased as soon as the file is opened
  • They are copied into a backup file automatically
  • They are kept until the program ends, then replaced

Which mode suits a log that should grow every day?

  • "a", which appends to the end of the file
  • "w", which writes each day's line into the file
  • No mode at all, because reading is the default
  • "r", which reads the file before adding a line

Why write a new file first and then replace the old one?

  • Because a file cannot be replaced while it is being read
  • Because replace makes the program run noticeably faster
  • So a crash while writing leaves the old file whole
  • Because Python refuses to open the same file twice

What does f.write("milk") put into the file?

  • The word milk followed by a line break
  • The word milk on a line of its own, with a number
  • A line break first, and then the word milk after it
  • Exactly the four letters of milk and nothing else

You got correct