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 `seek(0)` method do on a file object?
Answer: Moves the file cursor to the beginning
`seek(0)` repositions the file cursor to byte offset 0, which is the start of the file.
Which exception is raised when you try to open a file that does not exist using `open('missing.txt', 'r')`?
Answer: FileNotFoundError
`FileNotFoundError` (a subclass of `OSError`) is raised when the specified file cannot be found.
What is the output of the following code? ```python try: x = int('abc') except ValueError as e: print('caught') finally: print('done') ```
Answer: caught done
The `except` block prints 'caught', then the `finally` block always executes and prints 'done'.
Which mode string opens a binary file for both reading and writing without truncating it?
Answer: rb+
`'rb+'` opens a binary file for reading and writing while preserving existing content.
What does `f.tell()` return?
Answer: The current position of the file cursor in bytes
`tell()` returns an integer giving the current byte position of the file cursor.
Which built-in function can be used to suppress a specific exception and continue execution silently?
Answer: contextlib.suppress
`contextlib.suppress(ExceptionType)` is a context manager that silently swallows the specified exception.
What happens when you call `f.readlines()` on an empty file?
Answer: Returns an empty list []
`readlines()` on an empty file returns an empty list because there are no lines to read.