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('测试异常')
Please call me JiangYouDang!
浙公网安备 33010602011771号