Concepts / File Modes and Their Purposes

File Modes and Their Purposes

A file handle is a gateway between your program and the file on disk. It is not the file itself; it represents your program's connection to the file and manages operations such as writing and closing.

  • 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 Three-Step Contract

Writing to a file follows a strict sequence: open the file with a mode, write the data, and close the file. The mode states what you intend to do, the write operation places data into the file handle's buffer, and closing flushes that buffered data to physical storage. Each step has a different purpose, so skipping one breaks the process.

Key point

A file handle is a gateway between your program and the file on disk. It is not the file itself; it represents your program's connection to the file and manages operations such as writing and closing.

Opening with Write Mode

The open function takes a filename and a mode. The mode w means write mode. When a file already exists, opening it with w erases its entire existing contents before new data is written. This is intentional behavior, not an error. The file is then ready to receive new data through its file handle.

output.txtold contentsopen(..., w)write modeoutput.txtnew dataexisting filecontents erased before writing
What happens to existing contents when a file is opened in write mode, and where does new data go?

Writing Through the Buffer

After the file is open, write() inserts a string through the file handle. The data does not immediately appear on the physical storage device. Python first places it in a temporary buffer held in the program's memory. The buffer waits to be flushed to disk when the file is closed.

Code walkthrough
file_handle = open('output.txt', 'w')
characters_written = file_handle.write('Hello, World!')
file_handle.close()
  1. 1
    The first line creates a file handle for output.txt in write mode.
  2. 2
    The second line sends the string to the file handle's buffer and stores the integer returned by write().
  3. 3
    The third line flushes the buffered data and releases the file handle.
  • Open output.txt in write mode. Existing contents are erased.
  • Write the string and store the returned character count.
  • Close the handle so buffered data is flushed to physical storage.
write()string dataFile handleconnectionBufferprogram memoryclose()flush signalPhysical storagepersistent datasend datastore temporarilywait for closeflush
How data moves from a write() call through the file buffer and onto physical storage.

The return value of write() is an integer: the number of characters written. For example, the string Hello, World! contains 13 characters, including the comma and space, so write() returns 13. write() does not automatically add a newline. If separate pieces of text should appear on separate lines, include the newline character explicitly.

Before
characters_written = file_handle.write('Hello, World!')

The string is sent to the file handle's buffer.

After
characters_written == 13

The returned value records the number of characters written.

Closing Makes Data Persistent

Closing is not merely cleanup. It transfers buffered data from the program's memory through the operating system to the physical storage device, and it releases the file so other programs can access it. Until close() executes, data remains in the buffer. A program crash, power failure, or unexpected shutdown before the buffer is flushed can cause that data to vanish.

Open filedata in bufferclose()flush bufferClosed filedata on diskfinish writingflush and release
What changes between an open file with buffered data and a closed file whose data has been flushed?

Replacing or Preserving Content

Python provides two relevant modes for adding data. Write mode, w, erases existing contents and places new data into the resulting file. Append mode, a, preserves existing contents and adds new data at the end. The correct choice depends on whether the old contents are being replaced or extended.

werase, then writeapreserve, then addNew dataold content absentExisting plus newnew data at endreplace contentsadd at end
How do w and a differ in placement of new data and preservation of existing content?
Worked example

Choosing a Mode for a Log Entry

A file already contains earlier entries. You need to add one new entry without losing those earlier entries.

  1. 1
    Identify the required behavior

    The existing contents must remain, so replacing the file with w would be unsafe.

  2. 2
    Choose append mode

    Mode a preserves the existing contents and places new data at the end.

  3. 3
    Include a newline when needed

    write() does not add a newline automatically, so include one if the new entry should begin on its own line.

  4. 4
    Close the file

    Closing flushes the buffered entry to physical storage and releases the handle.

Result

Use append mode when adding data to an existing file without destroying what is already there.

Mistakes That Lose Data

  • Common mistake

    Opening an existing file with w when the intention is to add one item

    What it looks like

    Using write mode for a file whose earlier contents must be retained

    Why it fails

    Write mode erases the entire existing file before new data is written.

    Do this instead

    Use append mode a when new data should be added to the end.

  • Common mistake

    Expecting write() to add a newline automatically

    What it looks like

    Writing several names without including the newline character

    Why it fails

    write() writes the supplied string exactly and does not add newlines.

    Do this instead

    Include the newline character explicitly when separate lines are required.

  • Common mistake

    Leaving the file open after writing

    What it looks like

    Calling write() and ending the program without calling close()

    Why it fails

    The data can remain in the program's memory buffer instead of being flushed to physical storage.

    Do this instead

    Call close() immediately after finishing the writing operation.

  • Common mistake

    Trying to write after closing the handle

    What it looks like

    Calling write() again through the same handle after close()

    Why it fails

    The handle is no longer valid once it has been closed.

    Do this instead

    Finish all writing before close(), or open a file connection again when appropriate.

Check Your Understanding

EASY

A file named notes.txt already contains several lines. You need to add one more line while preserving every existing line. Which mode should you choose, what must you add if the new text belongs on its own line, and what final operation ensures the data is flushed?

Hints
  • Compare the effects of w and a on existing contents.
  • Remember that write() does not add a newline by itself.
  • The final operation transfers buffered data to physical storage.

What do you think happens?

If output.txt already contains text and is opened with w, will the new text be added after the old text?

  • Yes, the old text is preserved

  • No, the old text is erased first

Reveal answer
Answer:

No, the old text is erased first.

Write mode replaces the existing contents before new data is written. Append mode a is the mode that preserves existing contents and adds data at the end.

Essential Takeaways

  1. 1
    Opening with w prepares a file for writing but erases its existing contents.
  2. 2
    The write() method returns the number of characters written and does not add a newline automatically.
  3. 3
    Written data first enters a memory buffer rather than immediately reaching physical storage.
  4. 4
    Calling close() flushes the buffer to disk and releases the file handle.
  5. 5
    Use a when existing contents must be preserved and new data should be added at the end.

At a glance

  • Use the sequence open, write, and close for file-writing operations.
  • Mode w replaces existing contents, while mode a preserves them and adds data at the end.
  • write() returns the number of characters written and does not insert newlines automatically.
  • Closing the file flushes buffered data to physical storage and makes the writing operation complete.

Related concepts

More concepts starting with F