with在python中的作用Python 中的with语句是一种非常实用的语法主要用于资源管理确保资源在使用后能够被正确释放即使发生异常也不例外。自动管理资源开始时自动获取结束时自动释放。例如文件、网络连接、锁等无需手动调用close()或release()。提高代码可读性让代码更简洁、更安全。with语法with 表达式 [as 变量]: 代码块as 变量是可选的用于获取表达式返回的上下文管理器对象。工作原理上下文管理器协议任何对象只要实现了以下两个方法就可以用于with语句__enter__(self)进入with块时调用返回值赋给as后的变量。__exit__(self, exc_type, exc_val, exc_tb)退出with块时调用负责清理资源。参数用于处理异常。用法文件读写# 传统方式 f open(file.txt, r) try: content f.read() finally: f.close() # 使用 with with open(file.txt, r) as f: content f.read() # 文件会在 with 块结束后自动关闭with语句内部调用了文件的__enter__和__exit__方法即使读取过程中发生异常文件也会被安全关闭。自动管理锁from log import * import threading import time counter 0 lock threading.Lock() def increment(): global counter # 使用 with 语句自动管理锁的获取和释放 with lock: counter 1 info(Currrent thread: {0}, counter: {1}.format(threading.current_thread().name, counter)) # 创建10个线程 threads [] for _ in range(10): t threading.Thread(targetincrement) threads.append(t) t.start() for t in threads: t.join()