【学习笔记】《Python编程 从入门到实践》第10章:文件读写、异常处理与json存储

Python 入门实践 10:文件读写、异常处理与 JSON 存储

开篇:这篇解决什么问题

这一篇主要解决一个问题:程序运行完以后,数据怎么保存;程序出错时,怎么不要直接崩掉。

很多脚本不是只打印几行结果就结束,它可能要读取配置、写入日志、保存用户选择、处理文件不存在的情况。这时就会用到文件读写、异常处理和 JSON。

本篇你会学到什么

  • 如何使用with open()读取文件
  • 如何写入文件和追加内容
  • 如何用try-except处理常见错误
  • 如何用 JSON 保存和读取简单数据
  • 为什么要把代码重构成函数

场景案例:保存一个脚本配置

假设我们要保存一个任务配置:

importjson config={'task_name':'daily_report','owner':'alice','retry_count':3,}withopen('config.json','w',encoding='utf-8')asfile_object:json.dump(config,file_object,ensure_ascii=False,indent=2)

读取配置:

importjsonwithopen('config.json','r',encoding='utf-8')asfile_object:config=json.load(file_object)print(config['task_name'])

这就是很多脚本保存配置的基本方式。

知识点拆解

1. 读取整个文件

假设有一个文件notes.txt

Python is useful. File reading is common.

读取它:

withopen('notes.txt','r',encoding='utf-8')asfile_object:contents=file_object.read()print(contents)

with会在代码块结束后自动关闭文件,比手动关闭更稳。

2. 逐行读取

withopen('notes.txt','r',encoding='utf-8')asfile_object:forlineinfile_object:print(line.rstrip())

rstrip()用来去掉每行末尾的换行符。

3. 把文件内容读成列表

withopen('notes.txt','r',encoding='utf-8')asfile_object:lines=file_object.readlines()forlineinlines:print(line.rstrip())

这种写法适合后面还要多次处理这些行。

4. 写入文件

withopen('result.txt','w',encoding='utf-8')asfile_object:file_object.write('Task finished.\n')

注意:w模式会覆盖原文件内容。如果文件不存在,会创建新文件。

5. 追加内容

withopen('result.txt','a',encoding='utf-8')asfile_object:file_object.write('Another task finished.\n')

a表示追加,不会清空原文件。

6. 异常是什么

异常就是程序运行时出现的问题,比如除以 0、文件不存在、输入无法转成数字。

print(5/0)

这会触发ZeroDivisionError

7. 使用try-except

try:print(5/0)exceptZeroDivisionError:print("You can't divide by zero.")

程序不会直接崩掉,而是执行except里的处理逻辑。

8. 处理文件不存在

filename='missing.txt'try:withopen(filename,'r',encoding='utf-8')asfile_object:contents=file_object.read()exceptFileNotFoundError:print('File not found: '+filename)else:print(contents)

else里的代码只会在没有异常时执行。

9. 处理用户输入错误

user_input=input('Enter a number: ')try:number=int(user_input)exceptValueError:print('Please enter a valid number.')else:print(number*2)

只要涉及用户输入,就要考虑输入不符合预期的情况。

10. 使用 JSON 保存数据

写入 JSON:

importjson numbers=[2,3,5,7,11]withopen('numbers.json','w',encoding='utf-8')asfile_object:json.dump(numbers,file_object)

读取 JSON:

importjsonwithopen('numbers.json','r',encoding='utf-8')asfile_object:numbers=json.load(file_object)print(numbers)

JSON 适合保存列表、字典、字符串、数字这类简单数据。

11. 重构:把逻辑拆成函数

importjsondefload_config(filename):try:withopen(filename,'r',encoding='utf-8')asfile_object:returnjson.load(file_object)exceptFileNotFoundError:return{}defsave_config(filename,config):withopen(filename,'w',encoding='utf-8')asfile_object:json.dump(config,file_object,ensure_ascii=False,indent=2)

这样后面需要读取或保存配置时,就不用重复写文件操作代码。

初学者容易踩的坑

问题常见原因建议
文件找不到路径不对或文件不存在检查当前目录和文件名
写入后原内容没了使用了w模式想追加用a模式
中文乱码没指定编码使用encoding='utf-8'
JSON 读取失败文件内容不是合法 JSON确认文件格式正确
捕获异常太宽泛直接写except:尽量捕获明确异常类型

工作里能怎么用

场景用法
读取配置json.load()
保存执行结果写入文本或 JSON
记录日志追加写入文件
输入校验捕获ValueError
文件缺失兜底捕获FileNotFoundError

示例:读取配置并给默认值:

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 能让脚本更实用,测试能帮我们确认代码改动后仍然可靠。