Practice mode Python

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

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.