Python with open(): Close Files and Handle Errors
The with Statement: Open Files the Safe Way
The with statement opens a file and closes it for you when its block ends. You write with open(...) as f:, put the work in an indented block, and never call close() yourself.
Think of it like a door that closes by itself. You walk through, do what you came for, and when you leave, the door shuts behind you. You can't forget to close it.
The rules
with open("notes.txt", "w") as f:opens the file and names itf.- End the line with a colon, and indent the block under it, like an
ifor afor. - When the block ends, the file is closed. No
f.close()needed. - Use
withfor every file from now on. It's what Python programmers write.
with open("notes.txt", "w") as f:
f.write("Sunny\n")
f.write("Rocky\n")
with open("notes.txt") as f:
text = f.read()
print(text)Sunny Rocky
Two small blocks, no close() anywhere, and the file is still saved and read back properly.
Avoid: forgetting close()
f = open("notes.txt", "w")
f.write("Lucky")
reader = open("notes.txt")
print(len(reader.read()))
reader.close()0
The text was written, but the file was never closed, so it wasn't saved yet: the reader finds an empty file. Python keeps your writing in a waiting area (a buffer) and only puts it in the file for sure when the file is closed.
Good: let with close it
with open("notes.txt", "w") as f:
f.write("Lucky")
with open("notes.txt") as reader:
print(len(reader.read()))5
Common beginner doubt: "Is the text gone when the with block ends?" No. Only the file closes. Anything you stored in a variable inside the block, like text above, is still there afterwards.
with open(...) as f: closes the file for you when the block ends.