Overview
In this module, we dive into two crucial aspects of building real-world Python applications: File Handling and Exception Handling. You’ll learn how to manage external files (such as text documents and binary files) and handle runtime errors gracefully, which are both vital skills for writing robust and professional-grade code.
By the end of this module, you’ll not only know how to store and retrieve information from files but also how to prevent your programs from crashing when unexpected situations arise.
File Handling in Python
What is File Handling?
File handling refers to the ability of a program to create, read, write, and modify data stored in files. It allows persistent data storage, enabling your program to interact with external sources such as:
- Configuration files
- Logs
- User-generated content
- Application databases (basic ones)
Whether you’re storing notes, user preferences, or logs, mastering file handling is essential for real-world development.
File Modes in Python
Python offers several modes when opening a file, each with a specific use case:
Mode | Description |
---|---|
'r' | Read (default) – Opens the file for reading; throws an error if the file doesn’t exist |
'w' | Write – Opens the file for writing; creates the file or overwrites if it exists |
'a' | Append – Opens the file to append content at the end |
'x' | Exclusive creation – Fails if the file already exists |
'b' | Binary mode – Reads/writes binary (non-text) data |
't' | Text mode (default) – Works with readable text |
🔁 You can combine modes like 'rb'
(read binary) or 'wt'
(write text).
Understanding Text vs. Binary Files
This is a key concept when handling files in Python.
Text Files
- Stores plain text data in human-readable format
- Encoded in UTF-8 or similar encoding
- Examples:
.txt
,.csv
,.json
Binary Files
- Stores data in raw byte format (not human-readable)
- Used for images, videos, compiled code, etc.
- Examples:
.jpg
,.exe
,.mp3
Using the wrong mode (e.g., reading a binary file in text mode) can result in errors or corrupted data. Always choose your mode based on the type of content you’re working with.
Reading from a File
with open('data.txt', 'r') as file:
content = file.read()
print(content)
Other useful methods:
readline()
→ Reads the next linereadlines()
→ Reads all lines into a list
Writing to a File
with open('data.txt', 'w') as file:
file.write("Hello, Python learners!\n")
- Overwrites existing content if the file exists.
writelines()
can be used to write a list of strings.
Appending to a File
with open('data.txt', 'a') as file:
file.write("Appending a new line.\n")
This method is handy when you want to retain existing content and add more at the end.
Using the “with
” Statement
The “with
” statement ensures the file is properly closed after usage, even if an error occurs:
with open("file.txt") as f:
data = f.read()
No need to manually call file.close()
— it’s automatic!
Exception Handling in Python
What are Exceptions?
Exceptions are errors that occur at runtime, which may cause the program to stop unexpectedly unless they are handled properly.
Examples:
- Dividing by zero
- Accessing an undefined variable
- Trying to read a file that doesn’t exist
Try-Except Block
Basic usage:
try:
num = int(input("Enter a number: "))
print(100 / num)
except ValueError:
print("Invalid input – please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Each except
clause handles a specific error type.
Try-Except-Else-Finally Structure
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found.")
else:
print("File opened successfully.")
file.close()
finally:
print("This always runs.")
else
: Executes only if no exception occursfinally
: Executes whether there’s an error or not (great for cleanups)
Raising Custom Exceptions
def withdraw(balance, amount):
if amount > balance:
raise ValueError("Insufficient balance.")
return balance - amount
You can use raise
to throw an error manually when a specific condition is not met.
Mini Project: Notes Manager
Project Objective:
Create a command-line application that lets users add and view notes. The notes will be stored in a text file, and error handling will be used to manage invalid or missing data.
Key Features:
- Save notes to a text file
- Read and display saved notes
- Prevent crashes if the file is missing or input is empty
Sample Code Outline:
def add_note():
note = input("Enter your note: ")
if note.strip():
with open("notes.txt", "a") as f:
f.write(note + "\n")
print("Note added!")
else:
print("Empty note cannot be saved.")
def view_notes():
try:
with open("notes.txt", "r") as f:
notes = f.readlines()
if notes:
print("Your Notes:")
print("------------")
for line in notes:
print(line.strip())
else:
print("No notes to display.")
except FileNotFoundError:
print("No notes found.")
while True:
print("\n1: Add Note\n2: View Notes\n3: Exit")
choice = input("Choose an option: ")
if choice == '1':
add_note()
elif choice == '2':
view_notes()
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
✅ What You’ve Learned
- File handling basics: opening, reading, writing, and appending
- The difference between text and binary files
- Safe file operations using the
with
statement - Handling exceptions using try, except, else, and finally blocks
- Creating and raising your own exceptions
- Building a mini notes app combining file and error handling
Next Module: Functions and Modular Programming