python关键字“with”的用途是什么?

示例来自:http://docs.python.org/tutorial/inputoutput.html

>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

在python中,with关键字用于处理非托管资源(如文件流)。它类似于VB中的using语句。NET和c#。它允许您确保在使用资源的代码完成运行时“清理”资源,即使抛出异常。它为try/finally块提供了“语法糖”。

来自Python文档:

with语句澄清了以前使用try…最后块,以确保执行清理代码。 with语句是一个控制流结构,其基本结构为: 用expression[作为变量]: 使用块 表达式被求值,结果应该是一个支持上下文管理协议的对象(即具有__enter__()和__exit__()方法)。

根据Scott Wisniewski的评论更新了固定的VB调用。我确实搞混了。


来自Preshing on Programming博客的解释:

It’s handy when you have two related operations which you’d like to execute as a pair or more, with a block of code in between. The classic example is opening a file, manipulating the file, then closing it: 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.