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() |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。