["python"]
What is the python keyword "with" used for?

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 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. 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.