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__()函数。
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__()函数。
相关文章推荐
- Python 中的关键字with详解
- 正确理解python中的关键字“with”与上下文管理器
- 使用with关键字让你的Python代码更加Pythonic
- Python里面的with关键字
- Python基础学习:关键字with
- python中with关键字是个什么东西
- Python之with关键字
- 理解python "with"关键字
- python with关键字学习
- 完全理解Python关键字"with"与上下文管理器
- Python with 关键字详解
- python的with关键字及上下文管理器
- python With关键字用法(2)
- Python 中的with关键字使用详解
- python关键字 -- with
- Python yield assert with关键字
- python的with关键字
- Python 中的with关键字使用详解
- Really Simple HTTP Server with Python
- python3关键字