Python 使用 with 語句開啟文件
處理文件物件時使用 with 關鍵字是一種很好的做法。這樣做的好處是,即使在途中出現異常,文件也會在其套件完成後正確關閉。它也比編寫等效的 try-finally 區塊短得多。
In [1]: with open('/tmp/test','r') as f1:
...: print f1.read()
...:
hello, python
In [2]: f1.closed
Out[2]: True
In [3]: f2 = open('/tmp/test', 'r')
In [4]: print f2.read()
hello, python
In [5]: f2.closed
Out[5]: False
Also see PEP 343 -- The "with" Statement