Skip to content

9618 · 20.2

File Processing and Exception Handling

File processing lets your program save and load data, making it persistent. Exception handling is your program's safety net, catching errors gracefully without crashing.

Need to know

What you need to know

  • **`'r'` (Read):** Default mode. Opens a file for reading. Raises an error if the file does not exist.
  • **`'w'` (Write):** Opens a file for writing. Creates the file if it does not exist; overwrites it if it does.
  • **`'a'` (Append):** Opens a file for appending. Creates the file if it does not exist; adds new data to the end if it does.
  • **`'x'` (Create):** Creates a specific file. Raises an error if the file already exists.
  • **`'+'` (Update):** Can be added to a mode (e.g., `'r+'`, `'w+'`) to allow both reading and writing.
  • **`'b'` (Binary) / `'t'` (Text):** Specify binary or text mode. Text is the default.

Explanation

Files and Failsafes

  1. Open a file using a path and a specific mode (e.g., 'r' for read, 'w' for write).
  2. Perform operations like reading lines of text or writing new data into the file.
  3. Anticipate runtime errors by placing the file operations inside a 'try' block.
  4. Define 'except' blocks to catch specific errors and a 'finally' block to ensure cleanup, like closing the file.