File I/O and Exception Handling Flashcards
7 cards from real HACKERRANK practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 File I/O and Exception Handling flashcards as text
What does the `tell()` method return when called on an open file object?
Answer: The current byte position of the file pointer
`tell()` returns an integer representing the file pointer's current byte offset from the beginning of the file.
Which mode opens a file for exclusive creation, failing if the file already exists?
Answer: 'x'
Mode `'x'` (exclusive creation) opens the file for writing but raises `FileExistsError` if the file already exists.
How do you define a custom exception class named `AppError` in Python?
Answer: class AppError(Exception):
User-defined exceptions should subclass `Exception` (not `BaseException`) using standard class inheritance syntax.
What happens if an exception raised inside a `with` block is not handled?
Answer: The context manager's __exit__ is called, then the exception propagates
`__exit__` is always called (enabling cleanup), and if it returns a falsy value the exception continues to propagate up the call stack.
What is the output of `f.read()` called a second time on a file already read to EOF?
Answer: An empty string ''
After reaching EOF, `read()` returns an empty string `''` because there are no more bytes to read.
Which built-in Python module provides the `suppress` context manager to silently ignore specific exceptions?
Answer: contextlib
`contextlib.suppress(*exceptions)` is a context manager that suppresses the listed exception types if they occur inside the block.
When writing text to a file with `f.write(s)`, what does the method return?
Answer: The number of characters written
`write()` returns the number of characters (in text mode) or bytes (in binary mode) actually written to the file.