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:
- Open, Read, Write, and Close files using the
withstatement. - Handle common errors like
FileNotFoundError. - Master the
try-except-finallystructure.
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.
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.
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
- Ask the user for a filename and content.
- Attempt to write the content to the file.
- Use exception handling to catch any I/O errors.
- Add a feature to read a file and print "File not found" if it doesn't exist.
Step-by-Step Process
- Use
input()for filenames. - Wrap file operations in
try-except FileNotFoundError. - Use a loop to allow the user to read/write multiple files.
Expected Deliverables
note_taker.pysource code.