What is ‘With’ keyword in Python?

The ‘with’ keyword in Python is a control flow structure that simplifies error handling.

The ‘with’ statement is particularly used for clean-up tasks as you are working with unmanaged resources e.g. opening a file, performing some operations, and closing it (file streams).

The ‘with’ was added as an optional feature in Python 2.5. The following directive was required for using this feature:

 

from __future__ import with_statement

However, from version 2.6, the ‘with’ became a keyword and you do not need to enable it in order to use it.

Structure of with statement

Following is the general structure of using the Python with statement:

with expression [as variable]:

    #code to execute here

So, in the ‘with’ statement, the expression is evaluated.

In order to make it work, this should result in an object that supports __enter__() and __exit__() methods.

For example, the file object supports the __enter__() and __exit__() method, so you may use it there (as shown in the example below).

An example of using ‘with’ statement

In the following program, the with statement is used with the open function. A text file is given and its content will be displayed in the with block.

#Using with statement with a file

with open("test.txt") as with_demo:

    content = with_demo.read()

    print (content)
  • Normally, as you open the file in the system, you should close it by using the close() method.
  • However, in the program, we did not close it by using the close() method.
  • The ‘with’ statement has done this automatically for us, as such, it ensures cleaning up the resources.
  • Even if a Python exception occurs during the file opening, manipulation (as performing some operation) of the ‘with’ statement will execute the close() before the exception is caught.
You may learn more about the mechanism of how the ‘with’ statement works here.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!