您的位置:首页 > 编程语言 > Python开发

python with关键字

2013-12-18 12:16 274 查看
在python cookbook上看到这么段代码:

with open(filename) as f:

lines = (line.strip() for line in f)

for line in lines:

……

之前没有接触过with这个关键字,python 2.6前应该都不算是默认关键字,需要显示import(from __future__ importwith_statement)。

官方对with的解释是:

The 'with'

statement is a control-flowstructure whose basic structure is:

with expression [as variable]: with-block

其中的关键字应该是control flow structure,即流程控制,用以简化try finally的语句。

执行过程是,首先执行expresssion的__enter__()函数,然后执行with 块里的内容,最后执行__exit__()函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: