返回笔记

Python · 示例

Python 文件读写与异常处理

用上下文管理器读写 UTF-8 文本,并区分预期失败。

更新 2026.09.12Python / 文件 / 异常
目录

读取文本

显式使用 UTF-8,并让上下文管理器关闭文件。即使读取或处理过程抛出异常,离开 with 代码块时文件也会被关闭。

python
with open("note.md", encoding="utf-8") as source:
    text = source.read()

English summary

Use a Python context manager for file handling because it closes the file automatically after reading or writing, including when an exception occurs inside the with block.

错误边界

只捕获能够处理的异常,并保留文件位置和失败原因。不要用空的 except 隐藏错误。

关联内容