錯誤讀取文件
# 打開文件
f = open('file.txt')
for line in f:
# 讀取文件內(nèi)容 執(zhí)行其他操作
# do_something...
# 關(guān)閉文件
f.close()
java思維讀取文件
f = open('file.txt')
try:
for line in f:
# 讀取文件內(nèi)容 執(zhí)行其他操作
# do_something...
finally:
# 保證關(guān)閉文件
f.close()
使用with讀取文件
with open('file.txt') as f:
for line in f:
# do_something...
上下文管理器語法
with context_expression [as target(s)]:
 with-body
一個類在 Python 中浮定,只要實現(xiàn)以下方法相满,就實現(xiàn)了「上下文管理器協(xié)議」:
? enter:在進(jìn)入 with 語法塊之前調(diào)用,返回值會賦值給 with 的 target
? exit:在退出 with 語法塊時調(diào)用壶唤,一般用作異常處理
contextlib模塊可簡化上下文管理器協(xié)議
from contextlib import contextmanager
@contextmanager
def test():
print('before')
yield 'hello'
print('after')
with test() as t:
print(t)
# Output:
# before
# hello
# after