從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
周銳 閱讀(2729)
評論(0) 編輯 收藏 所屬分類:
Python