傳統的檔案存取try … catch … finally … :
file = open("example.txt", "r")
try:
content = file.read()
print(content)
finally:
file.close()
使用with ... :
with open("example.txt", "r") as file:
content = file.read()
print(content)
資源.close() 雖然看起來消失了,但其實 with 這個 keyword 會自動管理資源,就可以省去忘記要寫 close() 的問題。
除了檔案存取外,資料庫、網路連線等也可以使用with來管理資源,例如像是:with sqlite3.connect("example.db") as conn:
如果比較熟悉Java的話其實 with … 就是 Java SE(standard edition) 7 以後 try-with-resource 的概念。
參考連結: