python中with as語句的理解

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è)置,事后做清理工作。對于這種場景,Python的with語句提供了一種非常方便的處理方式。一個很好的例子是文件處理,你需要獲取一個文件句柄,從文件中讀取數(shù)據(jù),然后關(guān)閉文件句柄。

Without the with statement, one would write something along the lines of:

如果不用with語句,代碼如下:

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:

這里有兩個問題。一是可能忘記關(guān)閉文件句柄;二是文件讀取數(shù)據(jù)發(fā)生異常,沒有進(jìn)行任何處理。下面是處理異常的加強版本:

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:

雖然這段代碼運行良好,但是太冗長了。這時候就是with一展身手的時候了。除了有更優(yōu)雅的語法,with還可以很好的處理上下文環(huán)境產(chǎn)生的異常。下面是with版本的代碼:

with open("/tmp/foo.txt") as file:

data=file.read()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容