What is the with statement in Python?
The with statement makes sure that setup and cleanup are done automatically, even if an error happens in between. It works with a context manager, which is an object that has __enter__() and __exit__() methods. The most common use is opening files.
with open("notes.txt", "w") as f:
f.write("Hello")
print(f.closed)
Output:
Tutorials Class - Output Window
True
When the with block ends, the file is closed for you, so you do not need to call f.close(). It is also used for database connections, locks and temporary settings. See Python File Handling.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |