python with使用

使用with 打开文件,不用手动关闭文件。自动关闭文件

def read_file(file_path: str):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()
        print(content)


def main():
    file_path = "hello.txt"
    read_file(file_path)


if __name__ == '__main__':
    main()

 自定义python with上下文

class MyContextManager:
    def __enter__(self):
        print('进入上下文')
        return 'hello python'

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('离开上下文')
        if exc_type:
            print(f'捕获异常:{exc_val}')
        return True


if __name__ == '__main__':
    with MyContextManager() as my_context_manager:
        print(my_context_manager)
        raise ValueError('测试异常')

  

posted on 2025-12-26 00:06  luckygxf  阅读(1)  评论(0)    收藏  举报

导航