# What is the python keyword “with” used for?

## The Question :

546 people think this question is useful

What is the python keyword “with” used for?

Example from: http://docs.python.org/tutorial/inputoutput.html

>>> with open('/tmp/workfile', 'r') as f:
>>> f.closed
True



477 people think this answer is useful

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is “cleaned up” when the code that uses it finishes running, even if exceptions are thrown. It provides ‘syntactic sugar’ for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
with-block



The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski’s comment. I was indeed confusing with with using.

 with open('output.txt', 'w') as f: