python with

三个代码等价。with还可以很好的处理上下文环境产生的异常。

1
2
3
file = open("/tmp/foo.txt")
data = file.read()
file.close()
1
2
3
4
5
file = open("/tmp/foo.txt")
try:
    data = file.read()
finally:
    file.close()
1
2
with open("/tmp/foo.txt") as file:
    data = file.read()

 

posted @ 2014-11-06 10:02  tina_ma  阅读(200)  评论(0)    收藏  举报