Chapter 6 — Python File Handling & Exceptions

📚 Chapter Overview

Real programs interact with the real world. In this chapter, you will learn how to read and write text files and how to handle runtime errors gracefully using try-except blocks to prevent your scripts from crashing.

Learning Objectives:

6.1 Working with Files

Part 1 — Definition

File handling is an important part of any application. Python has several functions for creating, reading, updating, and deleting files. Using the with statement is the best practice as it automatically closes the file after the block of code is finished.

Part 2 — Syntax

with open("file.txt", "w") as f:
    f.write("Hello World")

with open("file.txt", "r") as f:
    content = f.read()

Part 3 — Example

Problem: Create a log file and add a timestamped entry.

script.py
import datetime

with open("log.txt", "a") as f:
    now = datetime.datetime.now()
    f.write(f"Access at {now}\n")

print("Log updated.")

Observation: The "a" mode stands for Append, which adds text to the end of the file without deleting the existing content.

Part 4 — Video

Video: Coming Soon


6.2 Exception Handling

Part 1 — Definition

An **Exception** is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Python uses the try-except block to "catch" these events and handle them so the program can continue.

Part 2 — Syntax

try:
    # Code that might fail
except ErrorType:
    # Code to handle failure
finally:
    # Always runs

Part 3 — Example

Problem: Handle a "Division by Zero" error.

script.py
try:
    num = int(input("Enter number: "))
    result = 100 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Please enter a valid number.")
else:
    print(f"Result is {result}")

Part 4 — Video

Video: Coming Soon


🏆 Chapter Challenge

Challenge Objective

Build a "Safe Note Taker" application.

Requirements

Step-by-Step Process

  1. Use input() for filenames.
  2. Wrap file operations in try-except FileNotFoundError.
  3. Use a loop to allow the user to read/write multiple files.

Expected Deliverables

Solve in Compiler