Skip to content

9618 · 20.2

File Processing and Exception Handling — common mistakes

Common exam mistakes on 9618 File Processing and Exception Handling. Learn what loses marks, then practise the topic with Examiner’s Ink.

Exam tip 1

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.

Why use `with open(...)` instead of `file = open(...)` and `file.close()`?

The with statement creates a context manager that guarantees the file will be closed automatically, even if your code raises an exception. If you manually open and close, you might forget to call close(), or an error might occur before close() is reached, leaving the file open and potentially leading to resource leaks or data corruption.

Should I just use a single `except:` to catch all errors?

No, this is generally bad practice. A bare except: (or except Exception:) catches everything, including system-exiting errors and keyboard interrupts. This can hide bugs and make your program difficult to debug. It's much better to catch specific exceptions that you know how to handle, like FileNotFoundError or ValueError.

What's the difference between `read()`, `readline()`, and `readlines()`?

read() reads the entire file content into a single string. readline() reads just one line from the file, including the newline character. readlines() reads all lines from the file and returns them as a list of strings.

How do I handle a file that uses a different character encoding?

The open() function has an encoding parameter. For example, if you know a file is encoded in UTF-8 (a very common standard), you would use open(myfile.txt,r,encoding=utf8)open('myfile.txt', 'r', encoding='utf-8'). Not specifying the encoding can lead to a UnicodeDecodeError if the file contains characters not supported by your system's default encoding.