Appending Data to Files: Mode 'a'
Write mode ('w') opens a file for writing and immediately truncates (erases) any existing content in the file.
Try it: Reading and Writing Text Files
How open() returns a file object with a position pointer, how read(), read(n), readline(), readlines() and for line in fh advance it (and return '' at the end), how 'w' and 'a' modes change the file, and why a closed file (after close() or a with block) can no longer be read.
How it works
- open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
- read() returns everything from the pointer to the end; read(n) at most n characters; readline() up to and including the next \n; each moves the pointer past what it returned.
- At the end of the file every read returns '' (an empty string), which is how loops know to stop; for line in fh reads line by line the same way.
- write() text waits in a buffer and reaches the file when it is closed (or the program ends); reading a 'w'/'a' file or writing an 'r' file raises io.UnsupportedOperation.
- close(), or leaving a with block, closes the file; any further read raises ValueError: I/O operation on closed file.
Default run (10 steps): Ready: notes.txt holds 4 lines (51 characters). Nothing is open yet. … Finished. notes.txt now holds "From: stephen\nSubject: meeting\nFrom: louis\nThanks!\n".
Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. One virtual text file with \n line endings (as on Linux/macOS), positions counted in characters (ASCII only), and a write buffer that is only flushed by close() or the end of the program.
Loading the simulation…
The Dangerous First Moment
Suppose notes.txt contains important data from yesterday. You run a Python script that opens the file in write mode to save today's notes. Before the script writes even one character, what happens to yesterday's data? The answer depends on the mode: opening an existing file with 'w' immediately erases its existing content.
What do you think happens?
If notes.txt already contains yesterday's notes, what will the file contain immediately after Python opens it with open('notes.txt', 'w')?
Reveal answer
The file is empty
Truncation happens at the instant the file is opened in 'w' mode, before any new data is written.
Opening in Write Mode
The second argument, 'w', selects write mode. Python opens the file for writing and immediately truncates it. Truncation means that any existing content is erased. This occurs before the program writes new data, so simply opening the file is enough to remove the old contents.
New Files and Existing Files
| Starting condition | Result of opening with 'w' |
|---|---|
| The file does not exist | Python creates the file |
| The file already exists | Python opens it and permanently removes its old data |
Write mode has different consequences depending on whether the named file already exists.
Write mode is useful when the intended result is a fresh file. For example, it can be used when generating a report, creating a configuration file, or saving computation output where the previous contents are no longer needed. If the file is new, Python creates it. If it already exists, its old contents are permanently removed.
Write Versus Append
Append mode, written as 'a', is the safer choice when existing content must remain. It preserves what is already in the file and positions new data at the end. Write mode, written as 'w', does the opposite with existing content: it clears the file so that new content can replace it.
| Mode | Existing content | Position of new data | Use when |
|---|---|---|---|
| 'w' | Erased when the file is opened | The file starts fresh | You want to replace the file's contents |
| 'a' | Preserved | At the end of the existing content | You want to add data without losing existing content |
The key difference between write mode and append mode is data preservation.
The two calls express different intentions. The first selects a mode that clears existing content. The second selects a mode that preserves existing content and adds new data after it. Choosing between them is therefore a data-preservation decision, not merely a spelling difference.
A File-State Prediction
Opening an Existing File with 'w'
Assume output.txt already contains data from a previous session. Predict the state of output.txt immediately after this statement runs: file = open("output.txt", "w")
- 1Identify the mode
The mode is 'w', which opens the file for writing.
- 2Check whether old content exists
The file is assumed to exist and already contain data.
- 3Apply truncation
Opening an existing file in write mode immediately erases its existing content.
- 4Stop before writing
No new data has been written yet, so the file is empty at this point.
Immediately after the open call, output.txt exists but contains no old data. The previous contents have already been removed.
Mistakes to Avoid
Common mistake Assuming truncation happens only when new text is written
What it looks likeOpening an existing file with open("output.txt", "w") and then checking the file before writing
Why it failsThe old content is erased at the instant the file is opened.
Do this insteadTreat the open call itself as the point at which existing data is removed.
Common mistake Using 'w' when the goal is to keep a file's history
What it looks likeOpening a notes file in 'w' mode to add today's notes to yesterday's notes
Why it failsWrite mode clears yesterday's notes instead of preserving them.
Do this insteadUse append mode, 'a', when new data must be added after existing content.
Common mistake Thinking 'w' and 'a' differ only in where the cursor starts
What it looks likeChoosing either mode without considering existing data
Why it failsThe modes have different data-preservation behavior: 'w' erases existing content, while 'a' preserves it.
Do this insteadChoose 'w' to replace contents and 'a' to preserve contents while adding at the end.
Common mistake Opening the wrong filename in write mode
What it looks likeUsing write mode on a file that contains important information
Why it failsExisting data in that file is permanently removed.
Do this insteadVerify the filename and use append mode if the existing data must be retained.
Choosing Intentionally
Decide what should happen to the existing file before selecting the mode. If the old content should be replaced entirely, choose 'w'. If it should remain and the new data should follow it, choose 'a'. Always verify the filename before opening a potentially important file in write mode.
A file named log.txt already contains records from earlier work. You need new records to remain alongside the old ones. Which mode should you choose, 'w' or 'a', and what will happen to the existing records when the file is opened?
Hints
- Ask whether the old records must be preserved.
- Recall which mode adds new data at the end.
Key Takeaways
- 1The 'w' mode opens a file for writing.
- 2When an existing file is opened in 'w' mode, Python immediately truncates it before any new data is written.
- 3If the file does not exist, Python creates it.
- 4The 'a' mode preserves existing content and adds new data at the end.
- 5Choose 'w' to replace a file deliberately and 'a' to add data without losing what is already there.
At a glance
- Opening an existing file with 'w' immediately erases its contents.
- This erasure occurs before any new data is written.
- Python creates the file if it does not already exist.
- Append mode 'a' preserves existing data and adds new data at the end.
- The correct mode depends on whether the old file contents should be replaced or preserved.