【发布时间】:2010-11-25 01:36:30
【问题描述】:
python 关键字“with”是干什么用的?
示例来自:http://docs.python.org/tutorial/inputoutput.html
>>> with open('/tmp/workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
【问题讨论】:
-
当您有两个相关的操作要成对执行并且无论它们之间的嵌套代码如何退出,都需要保证它们的执行时,这很方便。在此处查看示例:preshing.com/20110920/the-python-with-statement-by-example
-
因为我认为 Fredrik Lundh 的解释仍然是最好的解释之一,并且因为 effbot.org 现在“处于中断状态”——这是来自 archive.org 的快照之一:http://effbot.org/zone/python-with-statement.htm跨度>
-
effbot 的精彩文章,谢谢@ジョージ
标签: python