โ† All HACKERRANK Flashcard Decks

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
  1. Which built-in function is used to open a file in Python?

    Answer: open()

    The built-in `open()` function is used to open files in Python, returning a file object.

  2. What mode string opens a file for writing, creating it if it doesn't exist and truncating it if it does?

    Answer: 'w'

    'w' opens a file for writing, creates it if missing, and truncates existing content to zero length.

  3. What is the preferred Python idiom for opening a file to ensure it is properly closed afterward?

    Answer: with statement

    The `with` statement uses the context manager protocol to automatically call `close()` when the block exits, even on exceptions.

  4. Which file method reads all remaining lines of a file and returns them as a list of strings?

    Answer: readlines()

    `readlines()` reads from the current position to EOF and returns a list where each element is one line including the newline character.

  5. What does the 'b' flag signify when added to a file mode (e.g., 'rb' or 'wb')?

    Answer: Binary mode

    The 'b' flag opens the file in binary mode, reading/writing raw bytes instead of decoded text strings.

  6. Which method moves the file pointer to a specific byte position within an open file?

    Answer: seek()

    `seek(offset, whence)` repositions the file pointer to the given byte offset, enabling random access reads and writes.

  7. What exception is raised when Python cannot find the file you are trying to open?

    Answer: FileNotFoundError

    `FileNotFoundError` (a subclass of `OSError`) is raised when the specified file path does not exist.