This with
statement is used to execute code with an unmanaged resource that may raise an exception. This manages resources using it and removes them when the block finishes executing.
with resource as resource_name:
statement(s) # do something with the resource
Here,
Note: When using with
statement, resources that are file stream may raise an exception.
with
function uses open()
to work with the files in Python.
>>> with open('input.txt', 'r') as f:
... data = f.read()
Here, with open()
function a filepath and parameter ‘r’(read mode) is passed to use that file resource.