Concepts / Appending Data to Files: Mode 'a'

Appending Data to Files: Mode 'a'

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…

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')?

  • Yesterday's notes remain until new text is written

  • The file is empty

  • The new text is automatically added after yesterday's notes

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

python

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.

notes.txtYesterday's notesopen(..., 'w')File openednotes.txtEmptyopen in write modeexisting content erased
What happens to existing file content immediately after an existing file is opened with mode 'w'?

New Files and Existing Files

Starting conditionResult of opening with 'w'
The file does not existPython creates the file
The file already existsPython 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.

Existing dataRemovedExisting dataPreservedNew dataFresh file contentsNew dataAdded at the endreplaced byfollowed by
Where does new data go, and what existing data is preserved, when the same file is opened in 'w' versus 'a' mode?
ModeExisting contentPosition of new dataUse when
'w'Erased when the file is openedThe file starts freshYou want to replace the file's contents
'a'PreservedAt the end of the existing contentYou want to add data without losing existing content

The key difference between write mode and append mode is data preservation.

python

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

Worked example

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")

  1. 1
    Identify the mode

    The mode is 'w', which opens the file for writing.

  2. 2
    Check whether old content exists

    The file is assumed to exist and already contain data.

  3. 3
    Apply truncation

    Opening an existing file in write mode immediately erases its existing content.

  4. 4
    Stop before writing

    No new data has been written yet, so the file is empty at this point.

Result

Immediately after the open call, output.txt exists but contains no old data. The previous contents have already been removed.

Previous dataIn existing fileOpen with 'w'TruncateEmpty fileBefore new datafile openedold data erased
Before the code writes anything, what will an existing file contain after it is opened with mode 'w'?

Mistakes to Avoid

  • Common mistake

    Assuming truncation happens only when new text is written

    What it looks like

    Opening an existing file with open("output.txt", "w") and then checking the file before writing

    Why it fails

    The old content is erased at the instant the file is opened.

    Do this instead

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

    Opening a notes file in 'w' mode to add today's notes to yesterday's notes

    Why it fails

    Write mode clears yesterday's notes instead of preserving them.

    Do this instead

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

    Choosing either mode without considering existing data

    Why it fails

    The modes have different data-preservation behavior: 'w' erases existing content, while 'a' preserves it.

    Do this instead

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

    Using write mode on a file that contains important information

    Why it fails

    Existing data in that file is permanently removed.

    Do this instead

    Verify the filename and use append mode if the existing data must be retained.

Choosing Intentionally

Best practice

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.

EASY

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

  1. 1
    The 'w' mode opens a file for writing.
  2. 2
    When an existing file is opened in 'w' mode, Python immediately truncates it before any new data is written.
  3. 3
    If the file does not exist, Python creates it.
  4. 4
    The 'a' mode preserves existing content and adds new data at the end.
  5. 5
    Choose '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.

Related concepts

More concepts starting with A