Python Note 04

Python 文件与异常处理

学习文件读写、上下文管理器、JSON 保存和常见异常捕获方式。

1. 文件打开模式

`r` 表示只读,`w` 表示覆盖写入,`a` 表示追加写入,二进制读写可使用 `rb` 和 `wb`。

2. 读取文件

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

3. 按行读取

with open("notes.txt", "r", encoding="utf-8") as file:
    for line in file:
        print(line.strip())

4. 写入和追加

with open("output.txt", "w", encoding="utf-8") as file:
    file.write("Hello, Python!\\n")

with open("log.txt", "a", encoding="utf-8") as file:
    file.write("新增一条日志\\n")

5. JSON 文件读写

import json

student = {"name": "小明", "age": 18, "score": 95}

with open("student.json", "w", encoding="utf-8") as file:
    json.dump(student, file, ensure_ascii=False, indent=2)

6. 异常处理

try:
    num = int(input("请输入数字:"))
    print(100 / num)
except ValueError:
    print("请输入合法数字")
except ZeroDivisionError:
    print("不能除以 0")
finally:
    print("程序执行结束")

本章总结

文件读写推荐使用 `with open(...)`,异常处理可以让程序遇到错误时更稳定。