File & Exception Handling in Python

Master reading & writing files safely and handling runtime errors without crashes. Jump straight to any topic below.

File handling

File Operations Overview

🎯 Objectives of the Topic

• Master Files: Get hands-on with opening, reading, writing, and closing files in Python!

• Handle Errors Like a Pro: Learn how to catch and manage errors, ensuring your code runs smoothly even when things don’t go as planned.

đź“„ What is File Handling?

File Handling in Python is the ability to perform various operations on files, like reading from and writing to them. Files provide persistent storage, unlike variables which lose their values when a program ends.

File handling in Python allows you to:

1. Open files in different modes (read, write, append).

2. Read and write data in a variety of formats.

3. Close files to free up system resources.

Python’s built-in open() function is at the heart of this process, making your programs more robust, flexible, and useful.

📝 File Operations in Python

Let’s start with the basics of file handling! (1.5 hours)

• Opening Files

Use Python’s open() function to access a file.

Syntax: open(filename, mode), where:

• filename: The name of the file you want to work with.

• mode: The mode you want to open the file in.

Common modes:

• 'r': Read mode

• 'w': Write mode (creates new file or overwrites)

• 'a': Append mode (adds content without deleting existing data)

• 'rb', 'wb': Binary modes for non-text files

Example:

file = open("example.txt", "r") # Opens the file in read mode

• Reading Files

Python provides multiple ways to read file contents:

• .read(): Reads the entire file

• .readline(): Reads a single line at a time

• .readlines(): Reads all lines and returns a list

Example:

with open("example.txt", "r") as file:
    data = file.read()
print(data)

• Writing & Appending to Files

Writing is essential for saving data, like storing a user’s progress or keeping a record.

write() overwrites content, while append() adds new content without deleting.

Example:

with open("output.txt", "w") as file:
    file.write("Hello, Python!")

• Closing Files

Files should be closed after processing to release system resources.

Using Python’s with statement automatically handles closing:

with open("example.txt", "r") as file:
    data = file.read()
# File is automatically closed after this block

Exceptions handling

Exceptions Handling

⚠️ Exception Handling (1.5 hours)

Errors happen! To make sure your programs are error-proof and user-friendly, Python provides Exception Handling. It’s the art of catching errors and handling them gracefully.

• Basic Structure of try-except Blocks

• try: Runs code that might throw an error.

• except: Catches the error, allowing you to respond without crashing.

Example:

try:
    with open("nonexistent.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("File not found. Please check the filename.")

• Advanced Error Handling with finally and Custom Errors

• finally: Runs no matter what, often used to clean up (like closing a file).

• Custom Errors: Create custom exceptions for special cases (e.g., EmptyFileError).

Example with finally:

try:
    file = open("sample.txt", "r")
    data = file.read()
except FileNotFoundError:
    print("File not found.")
finally:
    file.close()

• Best Practices

• Use with for file handling: auto-close files, preventing potential leaks.

• Check file existence before reading/writing to avoid crashes.

• Handle specific exceptions over general ones (e.g., FileNotFoundError instead of Exception).

• Document error messages clearly for easier debugging and user support.

Download Notes

Custom Exceptions (Preview)

You can define your own exception classes to represent domain-specific error states. Example:

class EmptyFileError(Exception):
    """Raised when a required file is empty."""
    pass

def read_non_empty(path):
    with open(path,'r') as f:
        data = f.read()
        if not data.strip():
            raise EmptyFileError(f"'{path}' is empty")
        return data

try:
    read_non_empty('sample.txt')
except EmptyFileError as e:
    print('Problem:', e)

Extend Exception (or a subclass) and raise it where appropriate to make error handling clearer and more intentional.