9618 · 20.2
File Processing and Exception Handling flashcards
Revision flashcards for Cambridge 9618 File Processing and Exception Handling (syllabus 20.2). Flip, recall, then mark a real past-paper question.
Card
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.
Card
What is the difference between opening a file in 'w' mode and 'a' mode?
'w' (write) mode opens a file for writing. If the file exists, its contents are erased. If it doesn't exist, it's created. 'a' (append) mode opens a file to add content to its end. If the file doesn't exist, it's created.
Card
What is an exception in programming?
An event that occurs during the execution of a program that disrupts the normal flow of instructions. Examples include trying to divide by zero or accessing a file that doesn't exist.
Card
What is the purpose of a `try...except` block?
The `try` block lets you test a block of code for errors. The `except` block lets you handle the error, preventing the program from crashing.
Card
What does the `FileNotFoundError` exception signify?
It is raised when a program tries to open a file that does not exist at the specified path.
Card
Why is it important to close a file after use?
To free up system resources and ensure that any data buffered in memory is written to the disk. Failing to close a file can lead to data loss or corruption.
Card
What is the advantage of using the `with open(...) as ...:` syntax?
It automatically handles closing the file, even if exceptions occur within the block. This makes the code safer and cleaner.
Card
What does the `finally` keyword do in a `try...except` structure?
The `finally` block contains code that will be executed regardless of whether an exception occurred or not. It is ideal for cleanup actions, like closing a file.
Card
What is the difference between a text file and a binary file?
Text files store data as human-readable characters (e.g., ASCII, UTF-8). Binary files store data as a sequence of bytes (0s and 1s), which is not human-readable but is efficient for storing complex data like images or executables.
Card
What does the `ValueError` exception typically indicate when processing files?
It often occurs when you try to convert data read from a file into a different type, but the data is in an invalid format. For example, calling `int('hello')` after reading 'hello' from a file.
Card
What does the file method `readlines()` return?
It reads all lines from a file and returns them as a list of strings. Each string in the list represents one line and includes the trailing newline character `\n`.