Context Managers

with open("example.txt", "r") as file:
    content = file.read()
    print(content)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
Cell In[1], line 1
----> 1 with open("example.txt", "r") as file:
      2     content = file.read()
      3     print(content)

File /usr/local/Caskroom/miniconda/base/envs/llm/lib/python3.9/site-packages/IPython/core/interactiveshell.py:284, in _modified_open(file, *args, **kwargs)
    277 if file in {0, 1, 2}:
    278     raise ValueError(
    279         f"IPython won't let you open fd={file} by default "
    280         "as it is likely to crash IPython. If you know what you are doing, "
    281         "you can use builtins' open."
    282     )
--> 284 return io_open(file, *args, **kwargs)

FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
from contextlib import contextmanager

@contextmanager
def my_context():
    # Code to initialize the resource
    print("Initializing resource...")
    yield  # Indicates the end of the setup code and the start of the with block
    # Code to clean up the resource
    print("Cleaning up resource...")

# Using the context manager
with my_context():
    print("Inside the with block")
Initializing resource...
Inside the with block
Cleaning up resource...
CTRL + ENTER to send