📖 知识点
with 语法
with open("文件名", "模式", encoding="utf-8") as f:
# 这里写文件读写操作
f.write("内容")
# 离开with缩进块,文件自动关闭,无需 f.close()
核心特性:
当代码退出
with的缩进区域,自动执行 close (),释放资源哪怕缩进内代码抛出异常中断,文件依然会被自动关闭,非常安全
as f:把 open 返回的文件对象,赋值给变量 f
读取文件示例
with open("message.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 出了缩进,文件已经自动关闭
写入文件示例
with open("log.txt", "a", encoding="utf-8") as f:
f.write("with追加一行记录\n")
💡 新旧写法对比
旧写法:open → 读写 → f.close (),容易忘记关闭,异常时可能无法关闭
with 写法:自动关闭,简洁安全,工作项目优先使用 with
⚔️ Kata 实战任务
任务需求:
使用
with语句,r 模式打开message.txt,utf-8 编码read () 读取全部内容,打印文件内容
不需要手动写 close ()
运行查看输出
参考代码
# with 自动管理文件
with open("message.txt", "r", encoding="utf-8") as f:
content = f.read()
print("文件完整内容:")
print(content)
# 离开缩进,自动关闭文件
运行输出示例:
文件完整内容:
第一行:藏经篇练习
第二行:write覆盖写入
第三行:a追加模式,不覆盖旧内容
🧠 思考题
with 内部代码抛出异常,文件还会自动关闭吗?
以后写文件操作,推荐优先用 with 还是 open+close?理由是什么?
行者孙Python