Fatskills
Practice. Master. Repeat.
Study Guide: Computer Science - ICT Grade 10 Python File Handling and Exception Management
Source: https://www.fatskills.com/grade-10/chapter/computer-science-ict-grade-10-python-file-handling-and-exception-management

Computer Science - ICT Grade 10 Python File Handling and Exception Management

By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.

⏱️ ~6 min read

Grade 10 Computer Science (ICT) Study Guide: Python File Handling & Exception Management


1. The Driving Question

"You just wrote a program that asks 100 users for their high scores in a game, saves them to a file, and then reads them back to display the leaderboard. But what happens if the file gets deleted, the disk is full, or someone types ‘banana’ instead of a number? How do you keep your program from crashing—and how do you make sure the data isn’t lost forever?"


2. The Core Idea — Built, Not Listed

Imagine your school’s library checkout system. Every time a student borrows a book, the librarian writes the title, student name, and due date in a logbook (a file). At the end of the day, they close the logbook (save the file) so the ink doesn’t smudge. If a student tries to check out a book that’s already lost (a missing file), the librarian doesn’t scream and run away—they calmly say, "Sorry, that book isn’t available" (an exception). If the logbook’s pages are wet (a corrupted file), they don’t panic; they grab a backup (error handling).

In Python, files work the same way: - You open a file (like picking up the logbook) to read or write data.
- You close it (put the logbook back) to free up space and avoid mistakes.
- If something goes wrong (missing file, wrong data type), you catch the error (like the librarian’s calm response) instead of letting the program crash.

Key Vocabulary:
1. File Handle
- Definition: A temporary "connection" to a file that lets your program read or write data.
- Example: Like a librarian holding a logbook open to a specific page—you can’t write in it until you’ve "opened" it.
- College Note: In systems programming, file handles are low-level resources managed by the OS (e.g., file descriptors in Unix).


  1. Exception
  2. Definition: An event that disrupts the normal flow of a program (e.g., trying to read a file that doesn’t exist).
  3. Example: Like a vending machine jamming when you insert a crumpled dollar bill—it doesn’t explode, it just says "Error: Invalid input."
  4. College Note: Exceptions are objects in Python (e.g., FileNotFoundError inherits from OSError), and advanced error handling involves custom exception classes.

  5. Context Manager (with statement)

  6. Definition: A Python feature that automatically handles setup/cleanup (like opening/closing files) so you don’t forget.
  7. Example: Like a hotel keycard that automatically locks the door when you leave—you don’t have to remember to turn the key.
  8. College Note: Context managers use the __enter__ and __exit__ methods (dunder methods) and are used for database connections, locks, and more.

  9. Try-Except Block

  10. Definition: A structure that lets you "try" risky code and "catch" errors if they happen.
  11. Example: Like a lifeguard watching a pool—if someone starts drowning (an error), they jump in (the except block) instead of letting the pool close.
  12. College Note: In large systems, exception handling is layered (e.g., logging errors before re-raising them).

3. Assessment Translation

How This Appears on Assessments:
- Classroom (Formative): Short coding tasks (e.g., "Write a function that reads a file and returns the number of lines, handling FileNotFoundError").
- State/ICT Exams (Grade 10): Multiple-choice questions testing syntax (e.g., "Which code correctly opens a file for writing?") or debugging snippets with errors.
- AP Computer Science Principles (if applicable): Free-response questions where you must write code that handles files/exceptions (e.g., "Modify this function to log errors to a file").

Distractor Patterns in Multiple Choice:
- Confusing modes: r+ vs w+ (read/write vs write/overwrite).
- Forgetting to close files (memory leaks).
- Catching too broad an exception (e.g., except Exception instead of except ValueError).

Proficient Student Response Example:
Prompt: "Write a function read_scores(filename) that reads a file where each line is a player’s score (an integer). Return a list of scores. Handle cases where the file doesn’t exist or contains non-integer values."


def read_scores(filename):
scores = []
try:
with open(filename, 'r') as file:
for line in file:
try:
scores.append(int(line.strip()))
except ValueError:
print(f"Skipping invalid score: {line.strip()}")
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
return scores

Why This is Proficient:
- Uses with to auto-close the file.
- Nested try-except to handle both file and data errors.
- Provides user feedback (not silent failure).
- Returns a usable list (empty if errors occur).


4. Mistake Taxonomy

Mistake 1: Forgetting to Close Files (or Not Using with)
- Prompt: "Write code to write the string 'Hello' to a file named greeting.txt." - Wrong Response: python file = open('greeting.txt', 'w') file.write('Hello') # Forgot to close! - Why It Loses Credit: The file may not save properly (data loss), and the program wastes memory. Assessments dock points for resource leaks.
- Correct Approach: python with open('greeting.txt', 'w') as file:
file.write('Hello') # File auto-closes here

Mistake 2: Catching Too Broad an Exception
- Prompt: "Fix this code to handle cases where the file data.txt might not exist." - Wrong Response: python try:
with open('data.txt', 'r') as file:
print(file.read()) except Exception: # Too broad!
print("Error occurred.")
- Why It Loses Credit: Catches all errors (e.g., KeyboardInterrupt), hiding bugs. Assessments want specific exceptions.
- Correct Approach: python try:
with open('data.txt', 'r') as file:
print(file.read()) except FileNotFoundError:
print("Error: File not found.")

Mistake 3: Silent Failure (No User Feedback)
- Prompt: "Write a function that reads a file and returns its contents as a string. Handle errors gracefully." - Wrong Response: python def read_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except: # No feedback!
return ""
- Why It Loses Credit: The user has no idea why the function failed. Assessments require clear error messages or logging.
- Correct Approach: python def read_file(filename):
try:
with open(filename, 'r') as file:
return file.read()
except FileNotFoundError:
print(f"Error: '{filename}' not found.")
return None


5. Connection Layer

  1. Within Computer Science:
    File handling → Databases — Files are like raw database tables (rows = lines, columns = split data). Exception handling is like SQL transactions (roll back on error).

  2. Across Subjects:
    Exception management → Physics lab reports — In experiments, you "handle exceptions" (e.g., equipment failure) by noting them in your report instead of discarding data. Both fields require graceful degradation (doing the best you can with flawed inputs).

  3. Outside School:
    File modes (r, w, a) → Library checkout rulesr is like reading a book in the library (can’t change it), w is like checking out a book to rewrite it (erases the old one), and a is like adding a sticky note to the end (keeps the original).


6. The Stretch Question

"You’re writing a program that processes a file with 1 million lines. If the file is corrupted halfway through, your current try-except block will lose all the data processed so far. How would you design the program to save progress incrementally, so you can resume later without starting over?"

Pointer Toward the Answer:
Think like a video game saving your progress—you’d need to: 1. Chunk the file (process 1,000 lines at a time).
2. Log progress (e.g., write the last successful line number to a separate file).
3. Resume from the last checkpoint (skip lines you’ve already processed).
This is how big data tools (like Hadoop) handle failures at scale. The key is idempotency—making sure restarting doesn’t corrupt data.



ADVERTISEMENT