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.
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…
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.
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.
Writing Text and Counting Characters
Writing a Greeting
Write the text Hello, World! to output.txt and determine the value returned by write().
- 1Open
Open
output.txtwith mode 'w'. If the file already exists, its previous contents are erased. - 2Write
Pass the string Hello, World! to
write(). The method places the text into the file buffer. - 3Count
The string contains 13 characters, including the comma and space, so
write()returns 13. - 4Close
Call
close()to flush the buffered data to physical storage.
write() returns 13, and close() completes the transfer of the buffered text to the file.
13The 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.
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.
file_handle = open('output.txt', 'w')
file_handle.write('Saved text')
file_handle.close()- 1
open()creates the file handle and opensoutput.txtin write mode. - 2
write()places Saved text into the file handle's buffer. - 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 | Existing contents | Placement of new data | Typical purpose |
|---|---|---|---|
| 'w' | Erased | Written into the replacement file contents | Create or replace file contents |
| 'a' | Preserved | Added to the end | Add 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 likefile_handle = open('records.txt', 'w')Why it failsWrite mode erases the file's existing contents before new data is written.
Do this insteadUse 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 likefile_handle.write('Important data')Why it failsThe data may remain in the program's buffer instead of being flushed to physical storage.
Do this insteadCall file_handle.close() immediately after the final write.
Common mistake Expecting write() to add a newline automatically
What it looks likefile_handle.write('Ada') file_handle.write('Grace')Why it failswrite()inserts the supplied string but does not add a newline by itself.Do this insteadInclude the newline character explicitly, such as 'Ada\n'.
Common mistake Trying to write without first opening a file
Why it failsWriting is performed through a file handle created by
open().Do this insteadOpen the file with the required mode before calling write().
Common mistake Writing to a closed file handle
Why it failsAfter
close()executes, the file handle is no longer valid for writing.Do this insteadFinish all writes before closing, or open a file handle again when another writing operation is needed.
Choose the Correct Mode
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')?
Reveal 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
- 1Open the file with the mode that matches your intention.
- 2Remember that 'w' replaces existing contents, while 'a' preserves them and adds data at the end.
- 3Call
write()with the text to store. - 4Use the returned character count when debugging or logging if needed.
- 5Include newline characters explicitly when separate lines are required.
- 6Call
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.