代码点读机 / Python / with

with Python · 关键字

开辟一个上下文,离开前自动收拾残局,像住酒店:退房时房间会自动打扫干净。

怎么用

with 上下文管理器 as 变量:

小例子

with open('a.txt', 'w', encoding='utf-8') as f:
    f.write('hello')

运行结果

文件写入 hello 后自动关闭

提醒:处理文件、锁、网络连接时常用,能避免忘记关闭。

官方文档:https://docs.python.org/zh-cn/3/tutorial/errors.html#tut-cleanup-with

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条