Hackerrank File I/O and Exception Handling 1 — Questions and Answers
Question 1: Which built-in function is used to open a file in Python?
- file()
- open() (Correct answer)
- read()
- load()
Correct answer: open()
The built-in `open()` function is used to open files in Python, returning a file object.
Question 2: What mode string opens a file for writing, creating it if it doesn't exist and truncating it if it does?
- 'r'
- 'a'
- 'w' (Correct answer)
- 'x'
Correct answer: 'w'
'w' opens a file for writing, creates it if missing, and truncates existing content to zero length.
Question 3: What is the preferred Python idiom for opening a file to ensure it is properly closed afterward?
- try/finally block
- with statement (Correct answer)
- close() call in __del__
- atexit handler
Correct answer: with statement
The `with` statement uses the context manager protocol to automatically call `close()` when the block exits, even on exceptions.
Question 4: Which file method reads all remaining lines of a file and returns them as a list of strings?
- read()
- readline()
- readlines() (Correct answer)
- fetchall()
Correct answer: readlines()
`readlines()` reads from the current position to EOF and returns a list where each element is one line including the newline character.
Question 5: What does the 'b' flag signify when added to a file mode (e.g., 'rb' or 'wb')?
- Buffered mode
- Binary mode (Correct answer)
- Blocking mode
- Backup mode
Correct answer: Binary mode
The 'b' flag opens the file in binary mode, reading/writing raw bytes instead of decoded text strings.
Question 6: Which method moves the file pointer to a specific byte position within an open file?
- tell()
- seek() (Correct answer)
- move()
- position()
Correct answer: seek()
`seek(offset, whence)` repositions the file pointer to the given byte offset, enabling random access reads and writes.
Question 7: What exception is raised when Python cannot find the file you are trying to open?
- IOError
- FileNotFoundError (Correct answer)
- OSError
- MissingFileError
Correct answer: FileNotFoundError
`FileNotFoundError` (a subclass of `OSError`) is raised when the specified file path does not exist.
Which built-in function is used to open a file in Python?