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
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
In python the
with
keyword is used when working with unmanaged resources (like file streams). It is similar to theusing
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’ fortry/finally
blocks.From Python Docs:
Update fixed VB callout per Scott Wisniewski’s comment. I was indeed confusing
with
withusing
.