The with statement
Files, network connections and locks are resources: things you must give back when you're done. Forgetting to close a file can lose data that hasn't been written yet, and leaves the file locked on some systems.
The problem
Python
f = open("data.txt", "w")
f.write("important")
# if an error happened here, f.close() below would never run
f.close()
print("closed:", f.closed)You could protect it with try/finally:
Python
f = open("data.txt", "w")
try:
f.write("important")
finally:
f.close()
print("closed:", f.closed)That's correct, but wordy, and easy to forget.
The with statement
with does the same job in one line. The file is closed when the block ends, even if an exception happens inside it:
Python
with open("data.txt", "w") as f:
f.write("important")
print("closed:", f.closed)Python
try:
with open("data.txt", "w") as f:
f.write("first part")
raise RuntimeError("something went wrong mid-write")
except RuntimeError as e:
print("Error:", e)
print("Still closed properly:", f.closed)Several resources at once
Python
with open("source.txt", "w") as f:
f.write("line one\nline two\n")
with open("source.txt") as src, open("copy.txt", "w") as dst:
for line in src:
dst.write(line.upper())
with open("copy.txt") as f:
print(f.read())Not just files
Anything that needs setting up and tearing down can work with with. Such objects are called context managers. Examples you'll meet:
open()for files,- locks in threaded programs (
with lock:), - database connections and transactions,
decimal.localcontext()for temporary maths settings.
You can also write your own; that's the "Writing context managers" lesson in the last module.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.