Exceptions & Files · Question 13 · Medium

Why is with open("data.txt") as f: preferred over calling open() and close() separately?

  1. The file is read faster because with loads it fully into memory
  2. Any exception raised inside the block is silently ignored
  3. The file is closed automatically when the block ends, even if an exception occurs inside it
  4. The file is created automatically if it does not exist
Answer and explanation

Answer: C. The file is closed automatically when the block ends, even if an exception occurs inside it

Explanation: The with statement calls the file's clean-up code on every exit from the block, including when an error is raised. It does not hide the error or change how the file is opened.

Previous: read() is called three times on the same file-like object, first with a size… · Next: The only except clause below names TypeError, but the conversion fails in a…

Practise exceptions & files

Try a fresh set of exceptions & files questions with an explanation after every answer, free and without signing up: Exceptions & Files practice. Or sit a full placement mock test.

More exceptions & files questions

More python practice

Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope · Comprehensions & Generators

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge