Python’s with statement provides a very convenient way of dealing with the situation where you have to do a setup and teardown to make something happen. A very good example for this is the situation where you want to gain a handler to a file, read data from the file and the close the file handler.
有一些任務(wù),可能事先需要設(shè)置举户,事后做清理工作惧互。對(duì)于這種場(chǎng)景饮潦,Python的with語(yǔ)句提供了一種非常方便的處理方式。一個(gè)很好的例子是文件處理医清,你需要獲取一個(gè)文件句柄泣港,從文件中讀取數(shù)據(jù)售躁,然后關(guān)閉文件句柄。
Without the with statement, one would write something along the lines of:
如果不用with語(yǔ)句墨微,代碼如下:
file=open("/tmp/foo.txt")
data=file.read()
file.close()
There are two annoying things here. First, you end up forgetting to close the file handler. The second is how to handle exceptions that may occur once the file handler has been obtained. One could write something like this to get around this:
這里有兩個(gè)問(wèn)題道媚。一是可能忘記關(guān)閉文件句柄;二是文件讀取數(shù)據(jù)發(fā)生異常翘县,沒(méi)有進(jìn)行任何處理衰琐。下面是處理異常的加強(qiáng)版本:
file=open("/tmp/foo.txt")
try:
????? data=file.read()
finally:
???? file.close()
While this works well, it is unnecessarily verbose. This is where with is useful. The good thing about with apart from the better syntax is that it is very good handling exceptions. The above code would look like this, when using with:
雖然這段代碼運(yùn)行良好,但是太冗長(zhǎng)了炼蹦。這時(shí)候就是with一展身手的時(shí)候了羡宙。除了有更優(yōu)雅的語(yǔ)法,with還可以很好的處理上下文環(huán)境產(chǎn)生的異常掐隐。下面是with版本的代碼:
with open("/tmp/foo.txt") as file:
data=file.read()