Why do we use the with statement when working with files?
with guarantees the file is closed when the block ends, even if an exception occurs. It works through a context manager, an object with __enter__ and __exit__ methods, so cleanup does not depend on remembering to call close().
Explain it simply
A shop that uses an automatic door closes it behind you every time, even if you run out in a hurry. Opening a file the manual way is a door you must close yourself. If something goes wrong halfway, the door stays open and files stay locked or unflushed.
Example
with open("data.txt", "w", encoding="utf-8") as f:
f.write("hello")
print(f.closed) # Output: True
f2 = open("data.txt", encoding="utf-8")
try:
text = f2.read()
finally:
f2.close()
print(text) # Output: hello
with open("data.txt", encoding="utf-8") as a, open("copy.txt", "w", encoding="utf-8") as b:
b.write(a.read().upper())
print(open("copy.txt", encoding="utf-8").read()) # Output: HELLOThe try/finally version is what with replaces. The last example opens two files in one statement.
What to say in the interview
"with calls __enter__ at the start and __exit__ at the end, and __exit__ runs even on exceptions, so files, locks and connections are always released. It replaces try/finally boilerplate. It's not limited to files; locks, database connections and temporary directories use it too."
Common mistakes
- Using the file after the
withblock ends. It is closed, so reading raisesValueError.