There are some tasks that may need to be set up beforehand to do cleanup work afterwards. For this scenario, Python's with statement provides a very convenient way to handle it. A good example is file handling, where you need to get a file handle, read the data from the file, and then close the file handle.
The With-as expression greatly simplifies the work of writing finally every time.
When working with files, you can write the following very concise way. The important thing is that you don't have to think about when to fclose the problem.
With open ("/tmp/foo.txt") as file: = File.read ()
It is important to note that the code behind the elegance must be something that has already been done. Now that the file handle is inside this class, you have completed the work like enter and finally.
Reference:
Http://blog.kissdata.com/2014/05/23/python-with.html
With ... as ...