#with语句确保,不论是否运行错误都确保文件关闭,
with open('a.txt','r') as file: print(file.read())
#
MyContentMgr实现了特殊方法__enter__(),__exit__()称为该类对象遵守了上下文管理器协议
该类对象的实例对象,称为上下文管理器
MyContentMgr()
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方法被调用执行了',1/0) with MyContentMgr() as file: #相当于file=MyContentMgr() file.show()
#以后复制文件代码
with open('logo.png','rb') as src_file: #打开复制完关闭 with open('copy2logo.png','wb') as target_file: #打开写完,关闭 target_file.write(src_file.read())