1. 程式人生 > 程式設計 >Python with關鍵字,上下文管理器,@contextmanager檔案操作示例

Python with關鍵字,上下文管理器,@contextmanager檔案操作示例

本文例項講述了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
@contextmanager
def 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程式設計有所幫助。