What is the main advantage of using with open(…) as f: to work with a file?
Correct answer A. The file is closed automatically when the block ends, even if an exception occurs
Explanation
open() returns a context manager. The with statement calls its __enter__ method at the start and its __exit__ method when the block ends, which closes the file whether the block finishes normally or raises an exception. This replaces a manual try/finally with f.close().
Answer checked How we write and check questions
Discussion