Python 入门实践 10:文件读写、异常处理与 JSON 存储
开篇:这篇解决什么问题
这一篇主要解决一个问题:程序运行完以后,数据怎么保存;程序出错时,怎么不要直接崩掉。
很多脚本不是只打印几行结果就结束,它可能要读取配置、写入日志、保存用户选择、处理文件不存在的情况。这时就会用到文件读写、异常处理和 JSON。
本篇你会学到什么
- 如何使用
with open()读取文件 - 如何写入文件和追加内容
- 如何用
try-except处理常见错误 - 如何用 JSON 保存和读取简单数据
- 为什么要把代码重构成函数
场景案例:保存一个脚本配置
假设我们要保存一个任务配置:
python
import json
config = {
'task_name': 'daily_report',
'owner': 'alice',
'retry_count': 3,
}
with open('config.json', 'w', encoding='utf-8') as file_object:
json.dump(config, file_object, ensure_ascii=False, indent=2)
读取配置:
python
import json
with open('config.json', 'r', encoding='utf-8') as file_object:
config = json.load(file_object)
print(config['task_name'])
这就是很多脚本保存配置的基本方式。
知识点拆解
1. 读取整个文件
假设有一个文件 notes.txt:
text
Python is useful.
File reading is common.
读取它:
python
with open('notes.txt', 'r', encoding='utf-8') as file_object:
contents = file_object.read()
print(contents)
with 会在代码块结束后自动关闭文件,比手动关闭更稳。
2. 逐行读取
python
with open('notes.txt', 'r', encoding='utf-8') as file_object:
for line in file_object:
print(line.rstrip())
rstrip() 用来去掉每行末尾的换行符。
3. 把文件内容读成列表
python
with open('notes.txt', 'r', encoding='utf-8') as file_object:
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
这种写法适合后面还要多次处理这些行。
4. 写入文件
python
with open('result.txt', 'w', encoding='utf-8') as file_object:
file_object.write('Task finished.\n')
注意:w 模式会覆盖原文件内容。如果文件不存在,会创建新文件。
5. 追加内容
python
with open('result.txt', 'a', encoding='utf-8') as file_object:
file_object.write('Another task finished.\n')
a 表示追加,不会清空原文件。
6. 异常是什么
异常就是程序运行时出现的问题,比如除以 0、文件不存在、输入无法转成数字。
python
print(5 / 0)
这会触发 ZeroDivisionError。
7. 使用 try-except
python
try:
print(5 / 0)
except ZeroDivisionError:
print("You can't divide by zero.")
程序不会直接崩掉,而是执行 except 里的处理逻辑。
8. 处理文件不存在
python
filename = 'missing.txt'
try:
with open(filename, 'r', encoding='utf-8') as file_object:
contents = file_object.read()
except FileNotFoundError:
print('File not found: ' + filename)
else:
print(contents)
else 里的代码只会在没有异常时执行。
9. 处理用户输入错误
python
user_input = input('Enter a number: ')
try:
number = int(user_input)
except ValueError:
print('Please enter a valid number.')
else:
print(number * 2)
只要涉及用户输入,就要考虑输入不符合预期的情况。
10. 使用 JSON 保存数据
写入 JSON:
python
import json
numbers = [2, 3, 5, 7, 11]
with open('numbers.json', 'w', encoding='utf-8') as file_object:
json.dump(numbers, file_object)
读取 JSON:
python
import json
with open('numbers.json', 'r', encoding='utf-8') as file_object:
numbers = json.load(file_object)
print(numbers)
JSON 适合保存列表、字典、字符串、数字这类简单数据。
11. 重构:把逻辑拆成函数
python
import json
def load_config(filename):
try:
with open(filename, 'r', encoding='utf-8') as file_object:
return json.load(file_object)
except FileNotFoundError:
return {}
def save_config(filename, config):
with open(filename, 'w', encoding='utf-8') as file_object:
json.dump(config, file_object, ensure_ascii=False, indent=2)
这样后面需要读取或保存配置时,就不用重复写文件操作代码。
初学者容易踩的坑
| 问题 | 常见原因 | 建议 |
|---|---|---|
| 文件找不到 | 路径不对或文件不存在 | 检查当前目录和文件名 |
| 写入后原内容没了 | 使用了 w 模式 |
想追加用 a 模式 |
| 中文乱码 | 没指定编码 | 使用 encoding='utf-8' |
| JSON 读取失败 | 文件内容不是合法 JSON | 确认文件格式正确 |
| 捕获异常太宽泛 | 直接写 except: |
尽量捕获明确异常类型 |
工作里能怎么用
| 场景 | 用法 |
|---|---|
| 读取配置 | json.load() |
| 保存执行结果 | 写入文本或 JSON |
| 记录日志 | 追加写入文件 |
| 输入校验 | 捕获 ValueError |
| 文件缺失兜底 | 捕获 FileNotFoundError |
示例:读取配置并给默认值:
python
config = load_config('config.json')
retry_count = config.get('retry_count', 3)
print(retry_count)
小结
with open()可以安全打开文件read()读取全部内容,readlines()读取为列表w模式会覆盖文件,a模式会追加内容try-except可以处理运行时错误else适合放没有异常时才执行的代码- JSON 适合保存简单结构化数据
- 文件读写逻辑重复时,可以重构成函数
下一篇
下一篇继续讲测试。文件、异常和 JSON 能让脚本更实用,测试能帮我们确认代码改动后仍然可靠。