with Statement
noun
say it: “with STAYT-ment” /wɪð ˈsteɪtmənt/
A Python statement that opens something, such as a file, for the block under it and makes sure it gets closed when the block ends, even after an error.
What does the with statement do?
The with statement opens something, like a file, and makes sure it gets closed properly when the block ends, even if something goes wrong.
with open("scores.txt") as file:
print(file.read())
# the file is closed here automatically
In a sentence
- “The with statement closed scores.txt as soon as the block finished.”
- “Opening files in a with statement means no forgotten close().”
Level: Apprentice · More Python terms at this level
Updated