# 上下文管理with

import contextlib @contextlib.contextmanager
def myopen(file_path,mode): f = open(file_path,mode,encoding='utf-8') try: yield f finally: f.close() with myopen('index.html','r') as file_obj: print(file_obj.readline())