IT243 Programming with Python

Programming with PythonUnit 66 min read

File Handling & Exceptions in Python: I/O, Errors & Debugging

Unit 6 of Programming with Python covers reading/writing files (text, binary), exception handling (try-except), and debugging techniques—essential for robust programs that interact with external data or user input.

File Handling in Python

Files store persistent data beyond program execution. Python provides built-in functions to read/write files in text mode (strings) or binary mode (raw bytes).

Key File Operations

  1. Opening a File Use open() with mode flags:

    • 'r' (read), 'w' (write, overwrites), 'a' (append), 'r+' (read+write).
    • 'b' for binary (e.g., 'rb' for images).
    file = open("data.txt", "r")  # Opens in read mode
    

    Always close files with file.close() or use with (auto-closes):

    with open("data.txt", "r") as file:
        content = file.read()
    
  2. Reading/Writing Data

    • read(): Reads entire file as a string.
    • readline(): Reads one line.
    • readlines(): Returns a list of lines.
    • write()/writelines(): Writes data.
    with open("output.txt", "w") as file:
        file.write("Hello, TU!\n")
    

Binary Files (Images, PDFs)

Use 'rb'/'wb' modes. Example: Copying an image:

with open("input.jpg", "rb") as src, open("output.jpg", "wb") as dst:
    dst.write(src.read())

CSV Files (Common in Data)

Use csv module for structured data:

import csv
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)


Exception Handling

Errors disrupt programs. Python uses try-except blocks to handle exceptions gracefully.

Common Exceptions

Exception Cause Example
FileNotFoundError File doesn’t exist open("missing.txt", "r")
ValueError Invalid data type int("abc")
ZeroDivisionError Division by zero 10 / 0
IndexError List index out of range my_list[10]

Syntax

try:
    risky_operation()
except ExceptionType as e:
    handle_error(e)
else:
    runs_if_no_error()
finally:
    always_runs()

Example: Safe File Read

try:
    with open("data.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found! Using default data.")

MERMAID: Exception Handling Flowchart

flowchart TD
    A["Start"] --> B["Try Block"]
    B -->|"Success"| C["Else Block"]
    B -->|"Error"| D["Except Block"]
    D --> E["Log Error"]
    E --> F["Continue"]
    F --> G["Finally Block"]
    C --> G

Real-World Applications

1. eSewa (Nepal) – Transaction Logs

  • Idea Used: File handling ('a' mode) to append transaction records.
  • How: Each successful payment writes a log entry to transactions.log:
    with open("transactions.log", "a") as log:
        log.write(f"{user_id}, {amount}, {timestamp}\n")
    

2. Daraz – Order Processing Queue

  • Idea Used: File I/O to store pending orders in orders.txt.
  • How: Workers read orders line-by-line:
    with open("orders.txt", "r") as file:
        for order in file:
            process_order(order)
    

3. NTC – Network Error Handling

  • Idea Used: try-except to handle connection drops.
  • How: Retry logic for failed data transfers:
    for _ in range(3):
        try:
            send_data()
            break
        except ConnectionError:
            print("Retrying...")
    

Exam Tip

  • File Handling: Always use with to avoid resource leaks. Memorize modes ('r', 'w', 'a').
  • Exceptions: Know FileNotFoundError, ValueError, and IndexError. Practice nested try-except.
  • Common Pitfalls:
    • Forgetting to close files (use with).
    • Catching generic Exception (prefer specific types).
    • Not handling finally for cleanup (e.g., closing DB connections).


Worked Example: Bank Loan Calculator

Scenario: A bank stores loan data in loans.csv and calculates interest. Task: Read loans, compute interest, and save results.

import csv

def calculate_interest():
    loans = []
    with open("loans.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            loans.append({
                "id": row["id"],
                "amount": float(row["amount"]),
                "rate": float(row["rate"])
            })

    results = []
    for loan in loans:
        interest = loan["amount"] * loan["rate"] / 100
        results.append(f"{loan['id']},{interest:.2f}")

    with open("interest_results.csv", "w") as file:
        file.write("id,interest\n")
        file.writelines(f"{r}\n" for r in results)

calculate_interest()

Trace:

Step Action File State (loans.csv) Output (interest_results.csv)
1 Open loans.csv Read mode (Empty)
2 Read row {"id": "L1", "amount": 10000, "rate": 5} Data loaded into loans list (Empty)
3 Compute interest (500.00) Unchanged L1,500.00
4 Write results Unchanged id,interest\nL1,500.00

MERMAID: File Handling Steps for Loan Data

sequenceDiagram
    participant User
    participant Program
    participant loans_csv
    participant interest_csv

    User->>Program: Run `calculate_interest()`
    Program->>loans_csv: Open (read)
    loans_csv-->>Program: Return rows
    Program->>Program: Calculate interest
    Program->>interest_csv: Open (write)
    Program->>interest_csv: Write headers
    Program->>interest_csv: Write results
    Program->>interest_csv: Close

Based on the TU BIM syllabus for Programming with Python (IT243), unit 6.

Discussion

Loading…