Skip to content

9618 · 20.2

File Processing and Exception Handling — practice questions

Practice and worked examples for 9618 File Processing and Exception Handling. Short previews only — attempt the full question in MarkScheme against the official scheme.

Worked example 1

A text file named results.txt contains student scores, one per line. Some lines may be empty or contain non-numeric text. Write a Python program to read the scores, calculate the average of the valid scores, and print the result. The program must handle the case where results.txt does not exist and ignore invalid lines.

results.txt content:

85
92

78
---
65
Show solution outline
def calculate_average_score():
    total_score = 0
    valid_scores_count = 0
    try:
        with open('results.txt', 'r') as file:
            for line in file:
                # .strip() removes whitespace and newline characters
                cleaned_line = line.strip()
                if cleaned_line: # Check if line is not empty
                    try:
                        score = int(cleaned_line)
                        total_score += score
                        valid_scores_count += 1
                    except ValueError:
                        # This line is not a valid integer, so we ignore it.
                        print(f"Ignoring invalid line: '{cleaned_line}'")

        if valid_scores_count > 0:
            average = total_score / valid_scores_count
            print(f"Average score: {average:.2f}")
        else:
            print("No valid scores found.")

    except FileNotFoundError:
        print("Error: results.txt not found.")

# --- Execution ---
calculate_average_score()

# --- Expected Output ---
# Ignoring invalid line: '-- -'
# Average score: 80.00

Mark Scheme:

  • [1] try...except FileNotFoundError block used correctly.
  • [1] File opened for reading ('r') using with open().
  • [1] Iterates through lines of the file.
  • [1] Inner try...except ValueError to handle non-numeric data.
  • [1] Correctly calculates and accumulates total and count for valid scores.
  • [1] Correctly calculates and prints the average, handling division by zero.

Worked example 2

Write a procedure logevent(eventdescription)log_event(event_description) that takes a string and appends it, prefixed with a timestamp, to a file named events.log. The procedure must handle potential IOError exceptions that might occur if the file cannot be written to (e.g., due to permissions). If an error occurs, it should print an informative message to the console.

Show solution outline
import datetime

def log_event(event_description):
    """Appends a timestamped event to events.log."""
    try:
        # Get current time in a standard format
        timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        log_entry = f"[{timestamp}] {event_description}\n"

        # Use 'a' mode to append to the file
        with open('events.log', 'a') as log_file:
            log_file.write(log_entry)
        print("Event logged successfully.")

    except IOError as e:
        # Catching IOError is good for permission/disk full issues
        print(f"Error: Could not write to log file. {e}")

# --- Example Usage ---
# log_event("User 'admin' logged in.")
# log_event("System backup started.")

# --- File content of events.log after execution ---
# [2023-10-27 10:30:01] User 'admin' logged in.
# [2023-10-27 10:30:05] System backup started.

Mark Scheme:

  • [1] Procedure defined with correct parameter.
  • [1] try...except IOError block used to wrap file operation.
  • [1] File opened in append ('a') mode.
  • [1] Data is formatted correctly (e.g., timestamp + description).
  • [1] write() method used to add the formatted string to the file.
  • [1] Informative error message printed on exception.