Solving problem is about exposing yourself to as many situations as possible like What is the python keyword “with” used for? [duplicate] and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about What is the python keyword “with” used for? [duplicate], which can be followed any time. Take easy to follow this discuss.
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
From Python Docs:
withstatement clarifies code that previously would use
try...finallyblocks 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.
withstatement 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
Update fixed VB callout per Scott Wisniewski’s comment. I was indeed confusing
Explanation from the Preshing on Programming blog:
It’s handy when you have two related operations which you’d like to
execute as a pair, with a block of code in between. The classic
example is opening a file, manipulating the file, then
with open('output.txt', 'w') as f: f.write('Hi there!')
The above with statement will automatically close the file after the
nested block of code. (Continue reading to see exactly how the close
occurs.) The advantage of using a with statement is that it is
guaranteed to close the file no matter how the nested block exits. If
an exception occurs before the end of the block, it will close the
file before the exception is caught by an outer exception handler. If
the nested block were to contain a return statement, or a continue or
break statement, the with statement would automatically close the file
in those cases, too.