withwith 语句是 Python 中用于资源管理的重要特性它简化了异常处理确保资源在使用后正确关闭。# 传统方式 - 需要手动关闭fileopen(file.txt,r)try:contentfile.read()finally:file.close()# 必须手动关闭# with 语句 - 自动管理withopen(file.txt,r)asfile:contentfile.read()# 自动关闭# 文件操作withopen(file.txt,r)asfile:contentfile.read()# 文件会自动关闭即使发生异常# 同时打开多个文件withopen(input.txt,r)assource,open(output.txt,w)astarget:target.write(source.read())# Python 3.10 支持括号换行with(open(input.txt,r)assource,open(output.txt,w)astarget):target.write(source.read())# 用于数据库 连接import sqlite3withsqlite3.connect(database.db)asconn:cursorconn.cursor()cursor.execute(SELECT*FROM users)resultscursor.fetchall()# 连接自动提交并关闭# 用于lock rlock 锁