文件操作应使用 with 语句自动关闭文件。异常处理可以避免程序因单个错误而崩溃。

本节要点

  • open 的 mode 参数包括 r、w、a、b 等。
  • with open(...) 会自动释放文件资源。
  • 捕获具体异常类型,避免裸 except。

代码示例

try:
    with open("data.txt", "r", encoding="utf-8") as f:
        lines = [line.strip() for line in f if line.strip()]
    print(lines)
except FileNotFoundError:
    print("文件不存在")
except UnicodeDecodeError:
    print("文件编码不是 UTF-8")