Skip to main content

文件与异常

读写文件(推荐 with)

# 写
with open("demo.txt", "w", encoding="utf-8") as f:
f.write("hello\n")

# 读
with open("demo.txt", "r", encoding="utf-8") as f:
content = f.read()

with 会在结束时自动关闭文件,即使中途出错也尽量关闭。

常用模式:"r" 读、"w" 写(覆盖)、"a" 追加。文本场景指定 encoding="utf-8"

异常处理

try:
n = int("abc")
except ValueError as e:
print("转换失败:", e)
finally:
print("总会执行")
  • try:可能出错的代码
  • except:捕获特定异常类型
  • finally:无论成功失败都执行(清理资源)

也可以 raise 主动抛出:

def positive(x):
if x <= 0:
raise ValueError("x must be positive")
return x

最小完整示例

from pathlib import Path

path = Path("numbers.txt")
try:
text = path.read_text(encoding="utf-8")
total = sum(int(line) for line in text.splitlines() if line.strip())
print(total)
except FileNotFoundError:
print("文件不存在")
except ValueError:
print("存在无法转成整数的行")

要点

  1. 文件操作用 with(或 pathlib
  2. 捕获尽量具体的异常类型,避免裸 except:
  3. finally / 上下文管理器用于清理