Error Handling and Exceptions
A with statement, also called a context manager, provides a safer file-handling pattern.
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…
From Temporary Data to Saved Information
A running program can calculate results and process input, but those values exist only while the program is running unless the program saves them. Files provide a way to store information permanently so it can be retrieved and reused later. File operations therefore connect temporary in-memory work with persistent data on storage.
File work follows a consistent pattern: open the file, perform the required reading or writing, and close the file. The open() function returns a file object. That object is the program's interface to the file and provides operations such as read(), readline(), and write(). Closing finalizes changes and releases the file so other programs can use it.
A file object is not the file's entire content copied into a variable. It is an interface through which the program interacts with the file, including its current reading position.
Choosing a File Mode
The open() function takes a filename and a mode. The mode determines which kind of operation is allowed and what happens to content that is already in the file. Selecting the wrong mode can change the file's existing data, so the mode should be chosen before any file operation begins.
| Mode | Primary purpose | Effect on existing content |
|---|---|---|
| r | Read | Preserves existing content |
| w | Write | Erases existing file content |
| a | Append | Preserves existing content and adds data |
The three file modes described in the source material.
Following the File Pointer
When a file is read line by line, readline() retrieves one complete line at a time. The returned line includes its newline character when that character is present in the file. After the first call, the file pointer is at the start of the second line. Each later call retrieves the next line and moves the pointer forward.
Tracing three lines and the end of the file
Suppose a file contains three lines. Trace the values returned by successive readline() calls.
- 1First call
readline()returns line 1, including its newline character when present. The file pointer moves to the start of line 2. - 2Second call
readline()returns line 2 and moves the file pointer to the start of line 3. - 3Third call
readline()returns line 3 and moves the file pointer to the end of the file. - 4Fourth call
There is no remaining line, so
readline()returns an empty string. This is the signal that the end of the file has been reached.
The pointer advances once for each returned line. After the last line, the next readline() call returns an empty string, which can be used to stop reading.
End-of-file detection depends on recognizing the empty string returned by readline(). Checking whether the returned line has zero length tells the program when it should stop.
Stopping at End of File
A line-reading process must decide what to do after each readline() call. If the returned value contains a line, processing can continue. If the returned value is an empty string, the program has reached EOF and should stop the loop. The source describes this decision as checking whether the line length is zero and then breaking out of the loop.
Because readline() includes the line's newline character, displaying the returned line with an output operation that adds another newline can create double spacing. The source avoids that duplication by using print(line, end=''), so the output operation adds nothing after the already terminated line.
Writing and Closing Safely
Writing uses the write() method on a file object opened in write mode. The method accepts a string and places it in the file. Unlike print(), write() does not automatically add a newline, so a newline must be included in the string when separate lines are wanted.
A with statement, also called a context manager, provides a safer file-handling pattern. It automatically closes the file when the block exits. This happens both when processing completes normally and when an exception is raised, reducing the risk of leaving a file open.
Mistakes That Lose File Data
Common mistake Opening an existing file in w mode without intending to replace it.
What it looks likeA program selects write mode when it only needs to add a new record.
Why it failsWrite mode erases the existing file content.
Do this insteadUse append mode when existing content must be preserved and new data added.
Common mistake Treating an empty string from readline() as an ordinary line.
What it looks likeA reading process continues after readline() returns an empty string.
Why it failsAn empty string signals that the end of the file has been reached.
Do this insteadCheck for a zero-length result and stop reading when EOF is detected.
Common mistake Adding an extra newline while displaying a line returned by readline().
What it looks likeThe returned line is sent to print() without accounting for its existing newline character.
Why it failsreadline()includes the newline character at the end of the line, so another newline can produce double spacing.Do this insteadUse an output operation with end='' when preserving the line's existing ending.
Common mistake Forgetting to close a file.
What it looks likeA program finishes writing and never closes its file object.
Why it failsChanges may not be finalized, and the file may remain inaccessible to other processes.
Do this insteadCall close() after the work or use a with statement for automatic closing.
Practice the Trace
A file contains two lines. Describe the result of the first, second, and third readline() calls. For each call, state whether a line is returned, where the file pointer moves, and whether the reading process should continue or stop.
Hints
- Each nonempty result represents one line.
- After the second line, the pointer is at the end of the file.
- The next
readline()call returns an empty string and signals EOF.
A program must preserve a file's existing content and add new data. Which mode should it choose, and what closing strategy would protect the file if an exception occurs during processing?
Hints
- Compare the effects of r, w, and a on existing content.
- Consider the file mode that preserves current content while adding data.
- A with statement closes the file when the block exits, including when an exception is raised.
Key Takeaways
- 1Use
open(filename, mode)to obtain a file object, and choose the mode deliberately. - 2The r mode reads, w mode writes while erasing existing content, and a mode appends while preserving existing content.
- 3
readline()returns one complete line, including its newline character when present, and returns an empty string at EOF. - 4Closing a file finalizes changes and releases the file; a with statement performs this closing automatically, even when an exception occurs.
- 5Understanding the file pointer and checking for EOF makes line-by-line reading predictable and debuggable.
At a glance
- File operations use the sequence open, perform work, and close.
- The selected mode controls both permitted operations and the treatment of existing content.
- Successive
readline()calls move through the file one line at a time; an empty string indicates EOF. - Closing protects completed writes and releases the file, while a with statement handles closing automatically during normal or exceptional exits.