What is the python keyword "with" used for?
Example from: http://docs.python.org/tutorial/inputoutput.html
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
What is the python keyword "with" used for?
Example from: http://docs.python.org/tutorial/inputoutput.html
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
In python (and C#) the with keyword is used when working with unmanaged resources (like file streams). It creates the resource, performs the code in the block, then it closes the resource. It's similar to the Finally statement in a Try/Catch/Finally block, but without the error handling.
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).