Concepts / Error Handling and Exceptions

Error Handling and Exceptions

Files are opened using open(filename, mode), where mode controls read/write/append permissions and what happens to existing data.

  • Programming

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.

ModePrimary purposeEffect on existing content
rReadPreserves existing content
wWriteErases existing file content
aAppendPreserves existing content and adds data
allows readingreplaceskeeps and addsrreadExisting contentpreservedwwriteExisting contenterasedaappendExisting contentpreserved
How do read, write, and append modes differ in what they allow and what happens to existing file contents?

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.

next readline()next readline()next readline()Line 1returned by call 1Line 2returned by call 2Line 3returned by call 3EOFempty string
What changes in the file pointer's position after each readline() call, and where does it point when the end of the file is reached?

Tracing three lines and the end of the file

Suppose a file contains three lines. Trace the values returned by successive readline() calls.

First call: readline() returns line 1, including its newline character when present. The file pointer moves to the start of line 2.

Second call: readline() returns line 2 and moves the file pointer to the start of line 3.

Third call: readline() returns line 3 and moves the file pointer to the end of the file.

Fourth 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.

returns contentyesnext linereturns empty stringEOFreadline()retrieve one lineLinelength greater than zeroProcess linecontinue readingEmpty stringEOFStopbreak loop
What happens next when readline() reaches the end of the file, and how can the program decide whether to continue or stop?

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.

send stringwrite datacloseProgramdataFile objectwrite()Filestored contentClosed filechanges finalized
How does data move from the program into a file, and why must the file be closed before the program finishes?

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.

enter blockfinishesfailsblock exitsblock exitswith statementfile openedFile workread or writeNormal exitblock completesClosed fileautomatic closingExceptionprocessing fails
What control flow occurs when file processing finishes normally or an exception occurs, and how does automatic closing respond?

Mistakes That Lose File Data

  • Opening an existing file in w mode without intending to replace it.

    Write mode erases the existing file content.

    Fix: Use append mode when existing content must be preserved and new data added.

  • Treating an empty string from readline() as an ordinary line.

    An empty string signals that the end of the file has been reached.

    Fix: Check for a zero-length result and stop reading when EOF is detected.

  • Adding an extra newline while displaying a line returned by readline().

    readline() includes the newline character at the end of the line, so another newline can produce double spacing.

    Fix: Use an output operation with end='' when preserving the line's existing ending.

  • Forgetting to close a file.

    Changes may not be finalized, and the file may remain inaccessible to other processes.

    Fix: Call close() after the work or use a with statement for automatic closing.

Practice the Trace

EASY

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.
MEDIUM

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

  1. Use open(filename, mode) to obtain a file object, and choose the mode deliberately.
  2. The 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.
  4. Closing a file finalizes changes and releases the file; a with statement performs this closing automatically, even when an exception occurs.
  5. Understanding the file pointer and checking for EOF makes line-by-line reading predictable and debuggable.

Key Takeaways

  • 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.