Language
Version: 3.4.3
Categories
-
User Program Communication
-
Variables
-
Control Flow
-
Functions
-
Object Oriented Programming
Control Flow
With Statement in Python
Used to execute code with an unmanaged resource that may raise an exception. The with statement manages the resource, using it if successful and removing it when the block finishes executing.
Syntax
with resource as resource_var_name:
#do something with resource
Notes
An example of a resource that may raise an exception is a file stream.
Example
with open('input.txt', 'r') as f:
data = f.read()