python中的with語句是用來干嘛的?有什么作用?
with語句的作用是通過某種方式簡化異常處理,它是所謂的上下文管理器的一種
用法舉例如下:
with open('output.txt', 'w') as f: f.write('Hi there!')
當你要成對執行兩個相關的操作的時候,這樣就很方便,以上便是經典例子,with語句會在嵌套的代碼執行之后,自動關閉文件。這種做法的還有另一個優勢就是,無論嵌套的代碼是以何種方式結束的,它都關閉文件。如果在嵌套的代碼中發生異常,它能夠在外部exception handler catch異常前關閉文件。如果嵌套代碼有return/continue/break語句,它同樣能夠關閉文件。
我們也能夠自己構造自己的上下文管理器
我們可以用contextlib中的context manager修飾器來實現,比如可以通過以下代碼暫時改變當前目錄然后執行一定操作后返回。
from contextlib import contextmanager import os @contextmanager def working_directory(path): current_dir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(current_dir) with working_directory("data/stuff"): # do something within data/stuff # here I am back again in the original working directory
