QuestionQ3

VerifiedPython Basics for Data Analysis

You need to safely read the contents of a file called records.txt and save them in a list. The requirements are:

  • The file must be closed automatically after it is read.
  • The code should verify that the file exists before opening it.
  • Missing-file errors must be handled gracefully.

Which of the following is the most suitable way to do this in Python? Select the best answer.

Explanation

A with statement manages the file as a context manager and closes it when the block exits, including when an error occurs. Catching FileNotFoundError handles the missing-file condition at the actual attempt to open the file and allows an empty list to be assigned. This is more reliable than relying only on a separate existence check, because the file’s state can change between that check and open().

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!