Skip to main content

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.


with expression [as variable]:


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.

Submitted by devanshi.srivastava on July 13, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.


At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.