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.
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().
Open: Open output.txt with mode 'w'. If the file already exists, its previous contents are erased.
Write: Pass the string Hello, World! to write(). The method places the text into the file buffer.
Count: The string contains 13 characters, including the comma and space, so write() returns 13.
Close: 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()
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 |
Mistakes That Lose Data
Using 'w' when you intend to add information to an existing file
Write mode erases the file's existing contents before new data is written.
Fix:
Use append mode 'a' when existing contents must be preserved and the new data should go at the end.Forgetting to call close()
The data may remain in the program's buffer instead of being flushed to physical storage.
Fix:
Call file_handle.close() immediately after the final write.Expecting write() to add a newline automatically
write() inserts the supplied string but does not add a newline by itself.
Fix:
Include the newline character explicitly, such as 'Ada\n'.Trying to write without first opening a file
Writing is performed through a file handle created by open().
Fix:
Open the file with the required mode before calling write().Writing to a closed file handle
After close() executes, the file handle is no longer valid for writing.
Fix:
Finish 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
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
- Open the file with the mode that matches your intention.
- Remember that 'w' replaces existing contents, while 'a' preserves them and adds data at the end.
- Call write() with the text to store.
- Use the returned character count when debugging or logging if needed.
- Include newline characters explicitly when separate lines are required.
- 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.