WITH STATEMENT IN PYTHON

In this tutorial, we are going to learn about “with” statement in python along with syntax and  example. To get a clear understanding of the topic first let us understand what is with statement.

What is with statement

The with statement is used for resource management. In python with statement is used in exception handling to make the code cleaner and much more readable. And also it also ensures that resources are properly released when they are no longer needed, even if exception occurs. Simply A common example of using the with statement is opening a file and write to a file in python.

Syntax:

with open('example.txt', 't') as file:
data = file.read()

In this  “with” statement is used to open file and (‘example.txt’) is read mode.

NOTE:- In python, with statement  the file is automatically closed at the end of the block.

Example : 

try:
   with open('test.txt', 'r') as file:
        data=file.read() 
except value Error:
   print("Error occurred ") 
finally:
   print(" With close file")

 Output:-

With close file

In the example the with statement opens a file and assigns it to the variable. And the code block written the with statement is then executed and the file automatically

SIMPLE STATEMENT:

In simple with statement in python simplifies resources management and it replaces “try-final” blocks making code cleaner and more readable.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top