首页 > 代码库 > python with

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()

 

python with