Python编程:从入门到实践(第3版)

> 📖 **一起读书吧!** 加入《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()) # 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()
# 离开with块后,文件自动关闭

# ❌ 不推荐:手动关闭
f = open('file.txt')
contents = f.read()
f.close() # 如果上面报错,永远不会执行

官方文档:7.2.1. Methods of File Objectswith 确保文件正确关闭。

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-except-else(没有异常时执行else)
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]

# 写入JSON
filename = 'numbers.json'
with open(filename, 'w', encoding='utf-8') as f:
json.dump(numbers, f)

# 读取JSON
with open(filename, 'r', encoding='utf-8') as f:
loaded = json.load(f)
print(loaded) # [2, 3, 5, 7, 11, 13]

官方文档:json — JSON encoder and decoder


📚 官方文档参考


🎓 AI 编程实战课程

程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。