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

python