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.
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 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.
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.
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.
file_handle = open('output.txt', 'w')
characters_written = file_handle.write('Hello, World!')
file_handle.close()- 1The first line creates a file handle for
output.txtin write mode. - 2The second line sends the string to the file handle's buffer and stores the integer returned by
write(). - 3The third line flushes the buffered data and releases the file handle.
- Open
output.txtin 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.
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.
characters_written = file_handle.write('Hello, World!')The string is sent to the file handle's buffer.
characters_written == 13The 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.
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.
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.
- 1Identify the required behavior
The existing contents must remain, so replacing the file with w would be unsafe.
- 2Choose append mode
Mode a preserves the existing contents and places new data at the end.
- 3Include a newline when needed
write()does not add a newline automatically, so include one if the new entry should begin on its own line. - 4Close the file
Closing flushes the buffered entry to physical storage and releases the handle.
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 likeUsing write mode for a file whose earlier contents must be retained
Why it failsWrite mode erases the entire existing file before new data is written.
Do this insteadUse append mode a when new data should be added to the end.
Common mistake Expecting write() to add a newline automatically
What it looks likeWriting several names without including the newline character
Why it failswrite()writes the supplied string exactly and does not add newlines.Do this insteadInclude the newline character explicitly when separate lines are required.
Common mistake Leaving the file open after writing
What it looks likeCalling write() and ending the program without calling close()
Why it failsThe data can remain in the program's memory buffer instead of being flushed to physical storage.
Do this insteadCall close() immediately after finishing the writing operation.
Common mistake Trying to write after closing the handle
What it looks likeCalling write() again through the same handle after close()
Why it failsThe handle is no longer valid once it has been closed.
Do this insteadFinish all writing before close(), or open a file connection again when appropriate.
Check Your Understanding
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?
Reveal 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
- 1Opening with w prepares a file for writing but erases its existing contents.
- 2The
write()method returns the number of characters written and does not add a newline automatically. - 3Written data first enters a memory buffer rather than immediately reaching physical storage.
- 4Calling
close()flushes the buffer to disk and releases the file handle. - 5Use 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.