Opening Files for Reading: Mode 'r'
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…
A File with Yesterday's Notes
Imagine that notes.txt already contains important data from yesterday. You want a Python program to save today's notes, so you open the file using write mode, written as 'w'. The critical question is what happens before the program writes today's notes. Write mode does not preserve the old contents: opening the file immediately erases them.
What do you think happens?
Suppose file.txt already contains the text Old data. What will the file contain immediately after this line runs, before any write operation?
Reveal answer
An empty file
Opening an existing file in 'w' mode truncates it immediately. The old contents are erased before any new data is written.
The Instant State Change
The mode argument determines how Python works with a file. In 'w' mode, Python opens the file for writing and truncates it. Truncation means erasing the file's existing content. This happens at the instant the file is opened, before the program supplies any replacement text. If the file does not already exist, Python creates it instead.
After the open call completes, file refers to a file object that represents notes.txt opened in write mode. The important file-state change has already happened: if notes.txt existed, its previous contents are gone. The variable named file does not contain the old text; it represents the opened file that is now ready for writing.
Opening Before Writing
The order matters. First, Python opens the file in 'w' mode. Next, it truncates the file immediately. Only after that can the program write new content. Therefore, writing new data does not add to the old contents: it writes into a file whose previous contents have already been removed.
Replacing a File's Contents
The file report.txt already contains the text Previous report. Predict the contents after the following operations: open report.txt in 'w' mode, then write Fresh report.
- 1Open
The file is opened with the 'w' mode parameter.
- 2Truncate
The existing text is erased immediately, before the replacement text is written.
- 3Write
The text Fresh report is written into the now-empty file.
The file contains Fresh report. It does not contain Previous report.
Fresh reportWrite Mode and Append Mode
| Mode | Existing contents | Purpose |
|---|---|---|
| 'w' | Erased immediately when the file is opened | Replace the file's contents |
| 'a' | Preserved | Add new data at the end |
The key difference is whether data already in the file is preserved.
Choose 'w' when the intended result is a fresh replacement of the file's contents. Choose 'a' when the existing contents must remain and new data should be added at the end. Both modes can be used for writing, but they have opposite effects on data that is already present.
Mistakes with Existing Data
Common mistake Assuming 'w' adds new text after the old text.
What it looks likeA file contains Old notes, and the program opens it with 'w' before writing Today's notes.
Why it failsWrite mode truncates the file as soon as it is opened, so Old notes are erased before Today's notes is written.
Do this insteadUse 'a' when the existing text must be preserved and new text must be added at the end.
Common mistake Thinking truncation happens only when the write operation runs.
What it looks likeThe program opens a file in 'w' mode and performs no write operation.
Why it failsTruncation happens at the instant the file is opened, even if no new data is subsequently written.
Do this insteadPredict the file's state immediately after the open call: an existing file is already empty.
Common mistake Treating 'w' as unsafe in every situation.
What it looks likeA program needs to generate a completely fresh report each time it runs.
Why it failsReplacing a file is exactly the intended behavior when old contents are no longer needed.
Do this insteadUse 'w' deliberately when the entire file should be replaced, and verify the filename first.
Predict Before You Run
A file named output.txt already contains the text Result from yesterday. Predict the contents of output.txt immediately after this line runs: open('output.txt', 'w'). Then decide whether 'w' or 'a' is the appropriate mode if the goal is to keep yesterday's result and add today's result.
Hints
- Ask what happens at the instant an existing file is opened in 'w' mode.
- Compare the data-preservation behavior of 'w' and 'a'.
The prediction is an empty file immediately after the open call. If yesterday's result must remain, use 'a' rather than 'w', because append mode preserves existing content and adds new data at the end.
Key Takeaways
- 1The 'w' mode opens a file for writing.
- 2Opening an existing file in 'w' mode immediately erases its previous contents.
- 3Truncation occurs before any new data is written.
- 4If the file does not exist, Python creates it in 'w' mode.
- 5Use 'w' to replace contents and 'a' to preserve existing contents while adding data at the end.
At a glance
- Opening a file with 'w' prepares it for writing and immediately truncates an existing file.
- The old contents are erased before any new data is written.
- A nonexistent file is created when it is opened in 'w' mode.
- Use 'w' for replacement and 'a' when existing contents must be preserved and new data added at the end.