本文實例講述了Python with關鍵字,上下文管理器,@contextmanager文件操作。分享給大家供大家參考,具體如下:
demo.py(with 打開文件):
# open 方法的返回值賦值給變量 f,當離開 with 代碼塊的時候,系統會自動調用 f.close() 方法# with 的作用和使用 try/finally 語句是一樣的。with open("output.txt", "r") as f: f.write("XXXXX")
demo.py(with,上下文管理器):
# 自定義的MyFile類# 實現了 __enter__() 和 __exit__() 方法的對象都可稱之為上下文管理器class MyFile(): def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): print("entering") self.f = open(self.filename, self.mode) return self.f # with代碼塊執行完或者with中發生異常,就會自動執行__exit__方法。 def __exit__(self, *args): print("will exit") self.f.close()# 會自動調用MyFile對象的__enter__方法,并將返回值賦給f變量。with MyFile('out.txt', 'w') as f: print("writing") f.write('hello, python') # 當with代碼塊執行結束,或出現異常時,會自動調用MyFile對象的__exit__方法。
demo.py(實現上下文管理器的另一種方式):
from contextlib import contextmanager@contextmanagerdef my_open(path, mode): f = open(path, mode) yield f f.close()# 將my_open函數中yield后的變量值賦給f變量。with my_open('out.txt', 'w') as f: f.write("XXXXX") # 當with代碼塊執行結束,或出現異常時,會自動執行yield后的代碼。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python文件與目錄操作技巧匯總》、《Python文本文件操作技巧匯總》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
|
新聞熱點
疑難解答