这个问题在这里已有答案:
什么是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”用于什么?
示例来自:http://docs.python.org/tutorial/inputoutput.html
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
2 回答
Explanation from the Preshing on Programming blog:
在python中,在处理非托管资源(如文件流)时使用
with
关键字 . 它类似于VB.NET和C#中的using
语句 . 它允许您确保在使用它的代码完成运行时资源是"cleaned up",即使抛出异常也是如此 . 它为try/finally
块提供'syntactic sugar' .来自Python Docs:
根据Scott Wisniewski的评论更新固定的VB标注 . 我确实把
with
与using
混淆了 .