Interview Prep/Python for DevOps/Exceptions, context managers, files & logging

How does a `with` statement work, and why use it for files?

BeginnerConceptExceptions, context managers, files & logging
Answer

with calls the object's __enter__ at the start and guarantees __exit__ at the end, even if an exception is raised. For files, __exit__ closes the handle and flushes buffers.

with open("/etc/hosts", encoding="utf-8") as f:
    for line in f:
        ...

Without it, an exception mid-loop leaks the file descriptor; in a long-running service that eventually becomes OSError: [Errno 24] Too many open files. The same pattern is used for locks, SSH and DB connections, temp dirs and ThreadPoolExecutor.

All Python for DevOps questions Roadmap: Python for automation

More on Exceptions, context managers, files & logging