Concepts / Opening Files for Reading: Mode 'r'

Opening Files for Reading: Mode 'r'

Write mode ('w') opens a file for writing and immediately truncates (erases) any existing content in the file.

  • Programming
Interactive lab

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

  1. open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Educational simulation

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?

  • Old data

  • An empty file

  • Old data followed by new data

  • The file will be deleted

Reveal answer
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.

notes.txtYesterday's notesnotes.txtEmptyopen in 'w'
What changes between the file before opening and the file immediately after open('notes.txt', 'w')?
python

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

Open file'w' modeEmpty fileOld data erasedNew contentsWritten afterwardimmediatelythen
In what order do opening the file, erasing its previous contents, and writing new contents occur?

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.

Worked example

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.

  1. 1
    Open

    The file is opened with the 'w' mode parameter.

  2. 2
    Truncate

    The existing text is erased immediately, before the replacement text is written.

  3. 3
    Write

    The text Fresh report is written into the now-empty file.

Result

The file contains Fresh report. It does not contain Previous report.

python
Output
Fresh report

Write Mode and Append Mode

ModeExisting contentsPurpose
'w'Erased immediately when the file is openedReplace the file's contents
'a'PreservedAdd new data at the end

The key difference is whether data already in the file is preserved.

Old dataExisting fileOld dataExisting fileNew dataFile resultOld data plus newdataFile result'w' replaces'a' preserves and adds
How does the same new text affect a file when it is opened in 'w' mode versus 'a' mode?

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 like

    A file contains Old notes, and the program opens it with 'w' before writing Today's notes.

    Why it fails

    Write mode truncates the file as soon as it is opened, so Old notes are erased before Today's notes is written.

    Do this instead

    Use '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 like

    The program opens a file in 'w' mode and performs no write operation.

    Why it fails

    Truncation happens at the instant the file is opened, even if no new data is subsequently written.

    Do this instead

    Predict 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 like

    A program needs to generate a completely fresh report each time it runs.

    Why it fails

    Replacing a file is exactly the intended behavior when old contents are no longer needed.

    Do this instead

    Use 'w' deliberately when the entire file should be replaced, and verify the filename first.

Predict Before You Run

EASY

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

  1. 1
    The 'w' mode opens a file for writing.
  2. 2
    Opening an existing file in 'w' mode immediately erases its previous contents.
  3. 3
    Truncation occurs before any new data is written.
  4. 4
    If the file does not exist, Python creates it in 'w' mode.
  5. 5
    Use '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.

Related concepts

More concepts starting with O