In simple terms
A friendly intro before the formal notes — no formulas yet.
Files and Failsafes
File processing lets your program save and load data, making it persistent. Exception handling is your program's safety net, catching errors gracefully without crashing.
Imagine you're a librarian. A student requests a book (opening a file). You find the book and let them read it (processing). But what if the book isn't on the shelf? Instead of shouting 'ERROR!' and closing the library (crashing), you have a procedure: you check the system (handle a 'FileNotFoundError'), perhaps telling the student it's checked out or lost. This procedure is exception handling.
- 1
Open a file using a path and a specific mode (e.g., 'r' for read, 'w' for write).
- 2
Perform operations like reading lines of text or writing new data into the file.
- 3
Anticipate runtime errors by placing the file operations inside a 'try' block.
- 4
Define 'except' blocks to catch specific errors and a 'finally' block to ensure cleanup, like closing the file.
Explore the concept
Use the live diagram and synced steps — play it or tap a step card to walk through.
Key formulas
Tap any symbol to reveal exactly what it means and its units.
Full topic notes
Formal explanation with the rigour you need for the exam.
1. File Handling Fundamentals
File handling, or file I/O (Input/Output), is the process of creating, reading, updating, and deleting files. In Python, this begins with the open() built-in function. This function takes the file path as its first argument and the 'mode' as its second. The mode is a crucial string that tells Python what you intend to do with the file.
The best practice for opening files is using the with statement. This ensures the file is automatically closed when you are finished, even if errors occur.
# Writing to a file
with open('data.txt', 'w') as f:
f.write('Hello, world!\n')
# Reading from a file
with open('data.txt', 'r') as f:
content = f.read()
print(content)
'r' (Read): Default mode. Opens a file for reading. Raises an error if the file does not exist.
'w' (Write): Opens a file for writing. Creates the file if it does not exist; overwrites it if it does.
'a' (Append): Opens a file for appending. Creates the file if it does not exist; adds new data to the end if it does.
'x' (Create): Creates a specific file. Raises an error if the file already exists.
'+' (Update): Can be added to a mode (e.g., 'r+', 'w+') to allow both reading and writing.
'b' (Binary) / 't' (Text): Specify binary or text mode. Text is the default.
2. Understanding Exceptions
An exception is an error detected during execution. When your program encounters a situation it cannot cope with, like trying to open a non-existent file (FileNotFoundError) or converting an invalid string to a number (ValueError), Python 'raises' an exception. If unhandled, this exception will halt your program and display an error message. Exception handling is the process of catching these exceptions and executing specific code to respond, allowing the program to continue running or to terminate gracefully.
try:
# Code that might raise an exception
<risky_operation>
except <SpecificExceptionType>:
# Code to run if that specific exception occurs
<error_handler_code>
finally:
# Code that runs no matter what (e.g., cleanup)
<cleanup_code>
3. Combining File I/O and Exception Handling
Combining these two concepts is fundamental for writing robust, real-world applications. You should always assume that a file operation could fail. The disk could be full, the file might be locked by another program, it might not exist, or you may not have permission to access it. Wrapping your file I/O code in try...except blocks is not optional; it is a requirement for professional-quality code.
In Paper 4, you will almost certainly be asked to read from or write to a text file. Marks are often awarded for robust solutions. This means anticipating errors! Always consider what could go wrong: What if the file isn't there? What if the data is in the wrong format? Add try...except blocks to handle these cases, even if the question doesn't explicitly ask for it. It demonstrates good practice and can earn you marks for robustness.
Worked examples
See the formulas applied — reveal one step at a time, like the exam.
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
- 1
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}'")
Write a procedure 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.
- 1
import datetime
How it all connects
The big idea sits in the middle — tap a linked idea to explore the link.
Tap a linked idea to see how it connects back to the main topic — that connection is what examiners reward.
Glossary
Try to recall each definition before you reveal it.
Quick check
Answer in your head first — then tap to check. No pressure.
Revision flashcards
Flip the card. Test yourself before the exam.
What is a file handle?
An object returned by the open() function that provides a connection to a file on the disk. All read and write operations are performed through this handle.
Key takeaways
Review these before you close the topic — retrieval beats re-reading.
- ✓
'r' (Read): Default mode. Opens a file for reading. Raises an error if the file does not exist.
- ✓
'w' (Write): Opens a file for writing. Creates the file if it does not exist; overwrites it if it does.
- ✓
'a' (Append): Opens a file for appending. Creates the file if it does not exist; adds new data to the end if it does.
- ✓
'x' (Create): Creates a specific file. Raises an error if the file already exists.
- ✓
'+' (Update): Can be added to a mode (e.g., 'r+', 'w+') to allow both reading and writing.
- ✓
'b' (Binary) / 't' (Text): Specify binary or text mode. Text is the default.
Practice — then mark it
The whole point: a real Cambridge question, marked mark-by-mark.
Test Your Knowledge on File & Exception Handling
Test Your Knowledge on File & Exception Handling
Extra simulations & links
PhET, GeoGebra and other curated tools — open in a new tab.
Frequently asked
Checkpoint
One marked question is worth ten re-reads — close the loop before you move on.
Reading it isn’t knowing it — prove it.
Before you move on: do Test Your Knowledge on File & Exception Handling on paper, snap a photo, and get examiner-style feedback on exactly where you win and lose marks.