在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__()函数。
with expression [as variable]:
其中的关键字应该是control flow structure,即流程控制, 用以简化try finally的语句。
执行过程是,首先执行expresssion的__enter__()函数,然后执行with 块里的内容,最后执行__exit__()函数。