一:with做了什么
with啟動了對象的上下文管理器
二:上下文管理器協議:
__enter__:進入
enter方法返回的結果,被as后面的變量接受,with ... as f
__exit__:退出
with中所有的語句執行完畢后,執行該方法
在python中所有實現了上下文管理器協議的對象,都可以使用with操作
三、初識
f = open("musen.txt","w")
f.close()
print("f的dir方法:",dir(f))
# 等同于如下
with open("test.txt","w") as f:
f.write("python")
image.png
四:自定義文件操作的上下文管理器協議
class MyOpen:
def __init__(self,filename,mode,encoding):
self.filename = filename
self.mode = mode
self.encoding = encoding
def __enter__(self):
print("--enter--方法")
self.f = open(self.filename,self.mode,encoding = self.encoding)
return self.f
def __exit__(self, exc_type, exc_val, exc_tb):
"""
:param exc_type: 異常類型
:param exc_val: 異常信息
:param exc_tb: 異常溯源對象
:return:
"""
print(exc_type)
print(exc_val)
print(exc_tb)
self.f.close()
print("--exit--方法")
with MyOpen("musen.txt","w",encoding = "utf-8") as f:
print(f.write('e23433 '))
# print(bbb)
print("-----end------")
image.png