โ† 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. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.