Back to teaching portfolio

Chapter 6 · File I/O & Exceptions

CSBP119 Practical Questions

Reading and writing files introduces runtime risk. The following scenarios require try/except handling and thoughtful messages so scripts fail gracefully.

Problem 1 · Attendance Import

Parse Attendance with Error Handling

Load attendance.txt (one student name per line). If the file is missing, warn the user without crashing. When data loads, show a count and the roster.

  1. Wrap the file operation in try/except FileNotFoundError.
  2. Strip blank lines.
  3. Print the results.
try:
    with open("attendance.txt", "r", encoding="utf-8") as fh:
        count = 0
        for line in fh:
            name = line.strip()
            if not name:
                continue
            count += 1
            print("-", name)
    print("Students present:", count)
except FileNotFoundError:
    print("attendance.txt not found. Please export the roster first.")
Problem 2 · Incident Logger

Append Notes with Timestamp

Create a script that asks for an incident summary and appends it to incidents.log alongside the current date/time. Handle permission errors gracefully.

  1. Use the datetime module for ISO timestamps.
  2. Open the file in append mode.
  3. Add exception handling for OSError.
from datetime import datetime

note = input("Incident summary: ").strip()
timestamp = datetime.now().isoformat(timespec="minutes")

try:
    with open("incidents.log", "a", encoding="utf-8") as outfile:
        outfile.write(f"{timestamp} - {note}\n")
    print("Incident recorded.")
except OSError as error:
    print("Unable to write to incidents.log:", error)
Problem 3 · Score Export

Save Quiz Scores with Validation

Prompt for quiz scores separated by spaces, validate that every token is numeric, then write the cleaned line to quiz_scores.txt.

  1. Read the raw string and split manually.
  2. Validate each token using str.isdigit().
  3. Write the normalized line on success; otherwise, report an error.
raw = input("Enter quiz scores separated by spaces: ").strip()
clean_line = ""
token = ""
index = 0

while index < len(raw):
    char = raw[index]
    if char == " ":
        if token:
            if not token.isdigit():
                print("Invalid entry:", token)
                token = ""
                break
            if clean_line:
                clean_line += " "
            clean_line += token
            token = ""
    else:
        token += char
    index += 1

if token:
    if token.isdigit():
        if clean_line:
            clean_line += " "
        clean_line += token
    else:
        print("Invalid entry:", token)
        clean_line = ""

if clean_line:
    try:
        with open("quiz_scores.txt", "a", encoding="utf-8") as outfile:
            outfile.write(clean_line + "\n")
        print("Scores saved.")
    except OSError as error:
        print("Could not save scores:", error)