Interview Q&A / Python

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why do we use the with statement when working with files?

SHORT ANSWER

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

python
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: HELLO

The 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 with block ends. It is closed, so reading raises ValueError.

#python#file-io#context-managers

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.