posts - 431,  comments - 344,  trackbacks - 0
从python2.1开始以后, 当一个新的语言特性首次出现在发行版中时候, 如果该新特性与以前旧版本python不兼容, 则该特性将会被默认禁用. 如果想启用这个新特性, 则必须使用 "from __future__import *" 语句进行导入. 比如在2.5下使用with特性.

from __future__ import with_statement

with open('test.txt', 'r') as f:
    for line in f:
        print line

with方式语句可以替换以前try..catch语句, 如果使用try..catch语句则为:
try:
    f = open('test.txt', 'r')
    for line in f:
        print line
finally:
    f.close()

而with代码块如果内部出现任何错误, 都将会自动调用close方法

如果上面的with代码块没有使用from __future__ import with_statement, 代码将会报错, 提示你这个功能在2.6中实现.
Warning: 'with' will become a reserved keyword in Python 2.6
posted on 2009-05-27 13:33 周锐 阅读(2709) 评论(0)  编辑  收藏 所属分类: Python

只有注册用户登录后才能发表评论。


网站导航: