Ch4. Python — File Handling & Exception Management
File Reading and Writing
# Write to a text file
with open("hello.txt", "w") as f:
f.write("Hello, Python!\n")
f.write("File writing test.\n")
# Read entire file
with open("hello.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("hello.txt", "r") as f:
for line in f:
print(line.strip())
# Append to file
with open("hello.txt", "a") as f:
f.write("Appended line.\n")
CSV File Handling
import csv
# Write CSV
data = [
["Name", "Age", "Score"],
["Alice", 25, 92],
["Bob", 30, 78],
["Charlie", 22, 88]
]
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
# Read CSV as dictionaries
with open("students.csv", "r") as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']}: {row['Score']}")
JSON File Handling
import json
# Write JSON
person = {
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding", "travel"]
}
with open("person.json", "w") as f:
json.dump(person, f, indent=2)
# Read JSON
with open("person.json", "r") as f:
loaded = json.load(f)
print(loaded["name"]) # Alice
print(loaded["hobbies"]) # ['reading', 'coding', 'travel']
Exception Handling
# Basic try-except
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except TypeError:
print("Error: Please provide numbers!")
return None
finally:
print("Calculation attempted.") # Always runs
print(divide(10, 2)) # 5.0
print(divide(10, 0)) # Error message + None
print(divide(10, "a")) # Error message + None
# File handling exceptions
try:
with open("nonexistent.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found")
except PermissionError:
print("No permission to access file")
Custom Exceptions
class InsufficientFundsError(Exception):
def __init__(self, amount, balance):
self.amount = amount
self.balance = balance
super().__init__(
f"Insufficient funds: have ${balance:,.2f}, need ${amount:,.2f}"
)
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(amount, balance)
return balance - amount
try:
result = withdraw(100, 200)
except InsufficientFundsError as e:
print(e) # Insufficient funds: have $100.00, need $200.00
Chapter 5 Preview
Next: Standard Library & Package Management — datetime, os, random, collections, pip, and virtual environments.
O
OIYO Editorial
Editorial DeskThe OIYO editorial desk researches money, law, lifestyle, and self-understanding topics against primary sources and public statistics. Every piece carries source notes and is reviewed on a regular cycle for accuracy and usefulness.