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代碼塊如果內(nèi)部出現(xiàn)任何錯(cuò)誤, 都將會(huì)自動(dòng)調(diào)用close方法
如果上面的with代碼塊沒(méi)有使用from __future__ import with_statement, 代碼將會(huì)報(bào)錯(cuò), 提示你這個(gè)功能在2.6中實(shí)現(xiàn).
Warning: 'with' will become a reserved keyword in Python 2.6