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