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.
More on Exceptions, context managers, files & logging
How does `try` / `except` / `else` / `finally` work?BeginnerWhy is a bare `except:` (or `except Exception: pass`) dangerous?BeginnerWhat is exception chaining, and what is `raise ... from`?IntermediateWhen should you define custom exception classes?IntermediateWhat is the EAFP vs LBYL style, and which does Python prefer?IntermediateHow do you write your own context manager?Advanced