iT邦幫忙

0

不再忘記 close() 資源,認識 with...as

  • 分享至 

  • xImage
  •  

傳統的檔案存取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 的概念。

參考連結:


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言