Python 速查手冊

4.14 複合陳述 with as

關鍵字 (keyword) withas 是針對內容管理員物件 (object) 簡化的語法,使之開啟內容管理員物件,不再使用後便會自動關閉,因為如果沒有關閉的話,在程式執行期間很有可能造成記憶體問題,也就是內容管理員物件會一直佔據記憶體空間,直譯器不會主動做資源回收。

所謂內容管理員物件就是具有定義 __enter__()__exit__() 兩個方法 (method) 的物件,像是檔案處理或是資料庫相關,注意兩個方法前後都被兩條底線包圍。

常用的內容管理員物件就是檔案物件,這裡用一個純文字檔案當例子,裡頭有五個英文句子,接下來會用內建函數 (built-in function) open() 開啟這個檔案

這邊來看到 with-as 的語法,首先 with-as 是放到 try-except 中,因為如果檔案不存在就會發起例外, with 後面空一格接上 open() ,再空一格接 asas 後空一格接檔案開啟後的檔案物件 file ,最後用 for-in 迴圈 (loop) 印出檔案內容

try:
    with open("quotes.txt", "r", encoding="UTF-8") as file:
        for line in file:
            print(line)
except:
    print("檔案不存在")

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:with01.py
# 功能:示範 with 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 with01.py
Hello world!
 
There is no spoon.
 
Manners maketh the man.
 
You need time to know, to forgive and to love.
 
And then be a simple man.
$

假設不用 with-as 來寫的話, try-except 最後就要加上 finally ,檔案物件 file 要呼叫 close() 方法好關閉檔案物件,實際上也就是利用 close() 執行 __exit__() 方法

try:
    file = open("quotes.txt", "r", encoding="UTF-8")
    for line in file:
        print(line)
except:
    print("檔案不存在")
finally:
    file.close()

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:with02.py
# 功能:示範 with 陳述
# 作者:張凱慶

於命令列執行以上程式,結果如下

$ python3 with02.py
Hello world!
 
There is no spoon.
 
Manners maketh the man.
 
You need time to know, to forgive and to love.
 
And then be a simple man.
$

相關教學影片

上一頁: 4.13 複合陳述 try except finally else
Python 速查手冊 - 目錄
下一頁:單元 5 - 函數
回 Python 教材首頁
回程式語言教材首頁