

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)本讲内容
- 读取整个文件和逐行读取
- with 语句(上下文管理器)
- 写入文件
- 异常处理 try-except
- 分析文本文件
- JSON数据存储
学习目标
读取文件、处理报错、存储数据 📁
1. 读取整个文件
1 2 3
| with open('pi_digits.txt', encoding='utf-8') as file: contents = file.read() print(contents.rstrip())
|
⚠️ 始终用 encoding='utf-8',否则Windows默认GBK编码会乱码。
官方文档:7.2. Reading and Writing Files
2. 逐行读取
1 2 3
| with open('pi_digits.txt', encoding='utf-8') as file: for line in file: print(line.rstrip())
|
读取到列表
1 2 3 4 5
| with open('pi_digits.txt', encoding='utf-8') as file: lines = file.readlines()
for line in lines: print(line.rstrip())
|
3. with 语句(自动关闭文件)
1 2 3 4 5 6 7 8 9
| with open('file.txt', encoding='utf-8') as f: contents = f.read()
f = open('file.txt') contents = f.read() f.close()
|
官方文档:7.2.1. Methods of File Objects — with 确保文件正确关闭。
4. 写入文件
1 2 3 4 5 6 7 8
| with open('programming.txt', 'w', encoding='utf-8') as file: file.write("I love programming.\n") file.write("Python is my favorite!\n")
with open('programming.txt', 'a', encoding='utf-8') as file: file.write("I also love finding meaning in large datasets.\n")
|
| 模式 | 说明 |
|---|
'r' | 读取(默认) |
'w' | 写入(覆盖) |
'a' | 追加 |
'r+' | 读写 |
5. 异常处理
1 2 3 4 5 6 7 8 9 10 11 12
| try: print(10 / 0) except ZeroDivisionError: print("除数不能为零!")
try: answer = int("42") except ValueError: print("输入的不是有效数字!") else: print(f"结果是 {answer}")
|
官方文档:8.3. Handling Exceptions
静默失败(不需要打印时)
1 2 3 4
| try: answer = int("hello") except ValueError: pass
|
6. 常见异常类型
| 异常 | 说明 | 常见场景 |
|---|
ZeroDivisionError | 除以零 | 10/0 |
ValueError | 值类型不对 | int("abc") |
FileNotFoundError | 文件不存在 | open("notexist.txt") |
IndexError | 索引越界 | list[100] |
KeyError | 字典键不存在 | dict["no_key"] |
1 2 3 4 5 6 7 8 9
| try: filename = 'alice.txt' with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f"文件 {filename} 不存在!") else: words = contents.split() print(f"{filename} 包含约 {len(words)} 个单词")
|
7. JSON 数据存储
1 2 3 4 5 6 7 8 9 10 11 12 13
| import json
numbers = [2, 3, 5, 7, 11, 13]
filename = 'numbers.json' with open(filename, 'w', encoding='utf-8') as f: json.dump(numbers, f)
with open(filename, 'r', encoding='utf-8') as f: loaded = json.load(f) print(loaded)
|
官方文档:json — JSON encoder and decoder
📚 官方文档参考
🎓 AI 编程实战课程
程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。