ScanSkill

with statement

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.

Syntax

with resource as resource_name:
    statement(s) # do something with the resource

Here,

  • resource: resource item when iterated over the resource_name.
  • statement(s): Block of code to be executed.

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.

Examples

>>> 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.