打开文件
with open('abc.txt', 'r') as f:
content = f.read()
print(content)
在上下文管理协议中
class Agree:
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
def do_something(self):
print('do something')
with Agree() as agree:
agree.do_something()
#使用装饰器
import contextlib
@contextlib.contextmanager
def open_file():
print('open file')
yield {}
print('end file')
with open_file() as open:
print('file')