Hackerrank File I/O and Exception Handling 4 — Questions and Answers
Question 1: What does the `seek(0)` method do on a file object?
- Closes the file and reopens it
- Moves the file cursor to the beginning (Correct answer)
- Reads the first line of the file
- Truncates the file to zero bytes
Correct 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.
Question 2: Which exception is raised when you try to open a file that does not exist using `open('missing.txt', 'r')`?
- IOError
- FileNotFoundError (Correct answer)
- OSError
- ValueError
Correct answer: FileNotFoundError
`FileNotFoundError` (a subclass of `OSError`) is raised when the specified file cannot be found.
Question 3: What is the output of the following code? ```python try: x = int('abc') except ValueError as e: print('caught') finally: print('done') ```
- caught
- done caught
- caught done (Correct answer)
- done
Correct answer: caught done
The `except` block prints 'caught', then the `finally` block always executes and prints 'done'.
Question 4: Which mode string opens a binary file for both reading and writing without truncating it?
- rb+ (Correct answer)
- wb
- ab+
- xb
Correct answer: rb+
`'rb+'` opens a binary file for reading and writing while preserving existing content.
Question 5: What does `f.tell()` return?
- The total size of the file in bytes
- The current position of the file cursor in bytes (Correct answer)
- The number of lines read so far
- The encoding of the file
Correct answer: The current position of the file cursor in bytes
`tell()` returns an integer giving the current byte position of the file cursor.
Question 6: Which built-in function can be used to suppress a specific exception and continue execution silently?
- contextlib.suppress (Correct answer)
- exception.ignore
- try.pass
- os.ignore_error
Correct answer: contextlib.suppress
`contextlib.suppress(ExceptionType)` is a context manager that silently swallows the specified exception.
Question 7: What happens when you call `f.readlines()` on an empty file?
- Raises an EOFError
- Returns None
- Returns an empty list [] (Correct answer)
- Returns an empty string ''
Correct answer: Returns an empty list []
`readlines()` on an empty file returns an empty list because there are no lines to read.
What does the `seek(0)` method do on a file object?