with语句(可以自动关闭资源 可以不用手动关闭)
print(type(open('a.txt','r')))
with open('a.txt','r') as file: #取别名
print(file.read())
#open('a.txt','r')为上下文表达式,它的对象是上下文管理器
with语句可以自动管理上下文资源
with 上下文表达式 as 别名
上下文管理器
#MyContentMgr实现了特殊方法 __enter__和__exit__,所以称该类对象遵守了上下文管理协议
# 该类对象的实例对象 称为上下文管理器
class MyContentMgr(object):#上下文管理器
def __enter__(self):
print('enter方法被调用了')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("exit方法被调用了")
#实例
def show(self):
print('show方法被执行了')
with MyContentMgr() as file:
file.show()
出错了 也会退出
拷贝用上下文管理器实现
with open('a.png','rb') as file_scr: #取别名
with open('c.png','wb') as file_tar:
file_tar.write(file_scr.read())