from __future__ import with_statement
with open('test.txt', 'r') as f:
for line in f:
print line
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