With Statement in Python

In Python, the with statement is used for exception handling by encapsulating common preparation to make the code cleaner and much more readable. 

The with statement provides a way for ensuring that a clean-up is always used. It is used when we are working with some unmanageable resources like file. It provides 'syntactic sugar' for  try...finally blocks . Opening of a file becomes very simple when we use with statements and it can also automatically close the file.

Syntax:

with expression [as variable]:
      with-block

Examples:

with open('output.txt', mode='w') as file_1:
    file_1.write('Hello, Welcome to Python!!')

In the above example  with statement will automatically close the file after the block of code.

The advantage of using with statement is that it is assures to close the file no matter the block of codes has exits or not. If any exception occurs before the end of the block, it will automatically close the file before the exception is caught by an outer exception handler.

Tags