--- tags: python, 陳述式 --- # With語句 Python 語言提供了 `with` 這個獨特的語法,可讓程式設計者更容易管理這些開啟的資源,在這樣的語法架構之下,Python 程式會自動進行資源的建立、清理與回收動作,讓程式設計者在使用各種資源時更為方便。 ## 基本語法 傳統上開啟一個檔案,我們會使用`open`函式 ```py # 開啟檔案 f = open(filename) # 關閉檔案 f.close() ``` 可是這種寫法會遇到當檔案無法執行的時候,或是因為檔案跑掉等其他**外在因素**導致程式直接中止,也因此可以使用[`try`](python_try語句.md)作為例外判定。 ```py f = open(filename) #需要為路徑加副檔名的型態 try: pass finally: # 關閉檔案 f.close() ``` 這種作法就萬無一失了,但是缺點是得自己輸入關閉的函式,也因此我們可以利用`with`的功能。 ```py with open(filename) as f: #撰寫針對該程式所需要做的任何事情 ```
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.