01With statement for files
main.py
with open("data.txt", "w") as f:
f.write("Python")
with open("data.txt") as f:
print(f.read())Output
Python
Python context managers and the with statement: manage resources safely, build custom managers, and use contextlib decorators.
with open("data.txt", "w") as f:
f.write("Python")
with open("data.txt") as f:
print(f.read())Python
class Timer:
def __enter__(self):
print("Start")
return self
def __exit__(self, *args):
print("End")
with Timer():
print("Working")Start Working End
from contextlib import contextmanager
@contextmanager
def tag(name):
print("<" + name + ">")
yield
print("</" + name + ">")
with tag("div"):
print("content")<div> content </div>