1. 程式人生 > >With語句是什麼

With語句是什麼

https://www.cnblogs.com/DswCnblog/p/6126588.html     #大神寫的

 

有一些事情,需要預先設定, 事後做清理工作,對於這種場景。python 有了with as 方法。例如開啟檔案

  1、

  file = open("/tmp/foo.txt")  #開啟

  data = file.read()   #讀

  file.close()  #關閉

  這樣會有兩個問題, 1、忘記關閉,讀取的時候發生異常

 

  2、file = open("/tmp/foo.txt")

     try:

      data = file.read()

    finally:

      file.close()

 

  3、with可以很好的處理上下文產生的異常、可以完美的解決兩個問題、1、讀取的時候產生的異常、2關閉問題

  with open("/tmp/foo.txt") as file:

    data = file.read()