class FileMag():
def __init__(self,filename):
self.filename=filename
self.f=None
def __enter__(self):
self.f=open(self.filename,encoding="utf-8")
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
if self.f:
self.f.close()
if __name__=="__main__":
with FileMag("a10_4.py") as book:
for i in book.readlines():
def __init__(self,filename):
self.filename=filename
self.f=None
def __enter__(self):
self.f=open(self.filename,encoding="utf-8")
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
if self.f:
self.f.close()
if __name__=="__main__":
with FileMag("a10_4.py") as book:
for i in book.readlines():
print(i)
定义一个管理文件资源对象的上下文管理器类,在进入时打开文件,退出时关闭文件,然后用with语句来使用这个上下文管理器,打开一个指定的文件,并输出其中的内容。
在每次使用时都不用重新打开和关闭文件。
其中在Python中实现上下文管理器的模块中还有
import contextlib
@contextlib.contextmanager
def ga(s,e):
print(s)
print(s+" "+e)
print(e)
if __name__=="__main__":
with ga("Start","End") as val:
print(val)