Computer Science•Chapter 6•3 min read

Python — Files, Serialization & Exceptions

O
OIYO EditorialContributor
6/8

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

An exception can carry structured context for the caller. Validate inputs before changing a balance: negative, zero, or non-finite amounts are invalid, while a valid amount exceeding the balance is a different failure.

from math import isfinite

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):
    # 2026-10-03: reject invalid inputs before arithmetic; negative withdrawals add funds.
    if not isfinite(balance) or balance < 0:
        raise ValueError("Balance must be finite and non-negative.")
    if not isfinite(amount) or amount <= 0:
        raise ValueError("Amount must be finite and positive.")
    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

For ordinary numeric inputs, withdraw(100, 25) returns 75; withdraw(100, -10) raises ValueError instead of returning 110. The function returns a new value and does not persist a transaction. Floating-point amounts are used only for this teaching example: production monetary software requires a defined decimal or integer-unit representation, rounding policy, and durable transaction handling.


Chapter 7 Preview

Next: NumPy, pandas & Data Quality.

O

OIYO Editorial

Editorial Desk

The 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.