Concepts / Handling File Errors and Exceptions

Handling File Errors and Exceptions

Writing to a file requires opening it with mode 'w', calling write() to insert data, and closing the file to flush the buffer to disk.

  • 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 File Sequence

Writing to a file follows a strict sequence: open the file with a mode, write the data, and close the file. Each step has a different job. Opening creates the program's connection to the file, writing places text into that connection, and closing finishes the operation by transferring buffered data to physical storage.

open()file handlewrite()textFile bufferprogram memoryclose()flushPhysical storagepersistent dataconnection readystores textbuffered dataflushes data
How does text move from write() into the file buffer and finally onto storage when close() is called?

Opening in Write Mode

The open function takes the filename and the mode as arguments. To write to a file, use mode 'w'. Python creates a file handle, which is the program's connection or gateway to the file. The handle knows the file's location and mode and manages communication with the file.

python
output.txtold contentsopen('w')write modeoutput.txtemptyopenerases contents
What happens to existing file contents when output.txt is opened with mode 'w' before new data is written?

Writing Text and Counting Characters

Worked example

Writing a Greeting

Write the text Hello, World! to output.txt and determine the value returned by write().

  1. 1
    Open

    Open output.txt with mode 'w'. If the file already exists, its previous contents are erased.

  2. 2
    Write

    Pass the string Hello, World! to write(). The method places the text into the file buffer.

  3. 3
    Count

    The string contains 13 characters, including the comma and space, so write() returns 13.

  4. 4
    Close

    Call close() to flush the buffered data to physical storage.

Result

write() returns 13, and close() completes the transfer of the buffered text to the file.

python
Output
13

The return value from write() is an integer representing the number of characters written. It can help with debugging or logging. The method does not automatically add a newline, so separate pieces of text will not move to separate lines unless you include the newline character yourself.

python

Buffering and Closing

Calling write() does not mean that the text is immediately on the physical storage device. The data first enters a temporary buffer in the program's memory. Calling close() tells Python and the operating system to flush that buffered data to physical storage. Closing also releases the file so other programs can access it.

Code walkthrough
file_handle = open('output.txt', 'w')
file_handle.write('Saved text')
file_handle.close()
  1. 1
    open() creates the file handle and opens output.txt in write mode.
  2. 2
    write() places Saved text into the file handle's buffer.
  3. 3
    close() flushes the buffer to physical storage and releases the file handle.

Write Mode Compared with Append Mode

Choose the mode according to what should happen to existing contents. Write mode, 'w', erases the file first and then places new data into it. Append mode, 'a', preserves the existing contents and adds new data to the end. Opening an existing file with 'w' when you intended to add one line can destroy everything already stored in that file.

Mode 'w'replace contentsMode 'a'preserve contentsNew textfile contentsOld text + new textfile contentswrites from beginningwrites at end
How does data placement differ when the same text is written using mode 'w' versus mode 'a'?
ModeExisting contentsPlacement of new dataTypical purpose
'w'ErasedWritten into the replacement file contentsCreate or replace file contents
'a'PreservedAdded to the endAdd data without destroying existing contents

The central difference between write mode and append mode

Mistakes That Lose Data

  • Common mistake

    Using 'w' when you intend to add information to an existing file

    What it looks like
    file_handle = open('records.txt', 'w')
    Why it fails

    Write mode erases the file's existing contents before new data is written.

    Do this instead

    Use append mode 'a' when existing contents must be preserved and the new data should go at the end.

  • Common mistake

    Forgetting to call close()

    What it looks like
    file_handle.write('Important data')
    Why it fails

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

    Do this instead

    Call file_handle.close() immediately after the final write.

  • Common mistake

    Expecting write() to add a newline automatically

    What it looks like
    file_handle.write('Ada')
    file_handle.write('Grace')
    Why it fails

    write() inserts the supplied string but does not add a newline by itself.

    Do this instead

    Include the newline character explicitly, such as 'Ada\n'.

  • Common mistake

    Trying to write without first opening a file

    Why it fails

    Writing is performed through a file handle created by open().

    Do this instead

    Open the file with the required mode before calling write().

  • Common mistake

    Writing to a closed file handle

    Why it fails

    After close() executes, the file handle is no longer valid for writing.

    Do this instead

    Finish all writes before closing, or open a file handle again when another writing operation is needed.

Choose the Correct Mode

EASY

A file named log.txt already contains several lines. You need to add one new line while keeping every existing line. Which mode should you use, and what additional character should you include if the new entry must appear on its own line?

Hints
  • One mode erases existing contents; the other preserves them and writes at the end.
  • write() does not create a newline automatically.

What do you think happens?

If output.txt already contains text, what happens when this line runs: open('output.txt', 'w')?

  • The old contents are preserved and new text is placed at the end.

  • The old contents are erased before new text is written.

  • The file handle is created but the file contents cannot change.

Reveal answer
Answer:

The old contents are erased before new text is written.

Mode 'w' is write mode. Its defined behavior is to erase existing file contents before writing new data.

Reliable File Writing

  1. 1
    Open the file with the mode that matches your intention.
  2. 2
    Remember that 'w' replaces existing contents, while 'a' preserves them and adds data at the end.
  3. 3
    Call write() with the text to store.
  4. 4
    Use the returned character count when debugging or logging if needed.
  5. 5
    Include newline characters explicitly when separate lines are required.
  6. 6
    Call close() after the final write so buffered data is flushed to physical storage.

Key Takeaways

  • File writing follows the sequence open, write, and close.
  • Opening an existing file with mode 'w' erases its contents; mode 'a' preserves them and adds data at the end.
  • write() returns the number of characters written and does not add a newline automatically.
  • Written data first enters a memory buffer, so close() is required to flush it to physical storage.
  • A file handle is the program's connection to the file, and it cannot be used for writing after it has been closed.

Related concepts

More concepts starting with H