【学习笔记】《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,encodingutf-8)asfile_object:json.dump(config,file_object,ensure_asciiFalse,indent2)读取配置importjsonwithopen(config.json,r,encodingutf-8)asfile_object:configjson.load(file_object)print(config[task_name])这就是很多脚本保存配置的基本方式。知识点拆解1. 读取整个文件假设有一个文件notes.txtPython is useful. File reading is common.读取它withopen(notes.txt,r,encodingutf-8)asfile_object:contentsfile_object.read()print(contents)with会在代码块结束后自动关闭文件比手动关闭更稳。2. 逐行读取withopen(notes.txt,r,encodingutf-8)asfile_object:forlineinfile_object:print(line.rstrip())rstrip()用来去掉每行末尾的换行符。3. 把文件内容读成列表withopen(notes.txt,r,encodingutf-8)asfile_object:linesfile_object.readlines()forlineinlines:print(line.rstrip())这种写法适合后面还要多次处理这些行。4. 写入文件withopen(result.txt,w,encodingutf-8)asfile_object:file_object.write(Task finished.\n)注意w模式会覆盖原文件内容。如果文件不存在会创建新文件。5. 追加内容withopen(result.txt,a,encodingutf-8)asfile_object:file_object.write(Another task finished.\n)a表示追加不会清空原文件。6. 异常是什么异常就是程序运行时出现的问题比如除以 0、文件不存在、输入无法转成数字。print(5/0)这会触发ZeroDivisionError。7. 使用try-excepttry:print(5/0)exceptZeroDivisionError:print(You cant divide by zero.)程序不会直接崩掉而是执行except里的处理逻辑。8. 处理文件不存在filenamemissing.txttry:withopen(filename,r,encodingutf-8)asfile_object:contentsfile_object.read()exceptFileNotFoundError:print(File not found: filename)else:print(contents)else里的代码只会在没有异常时执行。9. 处理用户输入错误user_inputinput(Enter a number: )try:numberint(user_input)exceptValueError:print(Please enter a valid number.)else:print(number*2)只要涉及用户输入就要考虑输入不符合预期的情况。10. 使用 JSON 保存数据写入 JSONimportjson numbers[2,3,5,7,11]withopen(numbers.json,w,encodingutf-8)asfile_object:json.dump(numbers,file_object)读取 JSONimportjsonwithopen(numbers.json,r,encodingutf-8)asfile_object:numbersjson.load(file_object)print(numbers)JSON 适合保存列表、字典、字符串、数字这类简单数据。11. 重构把逻辑拆成函数importjsondefload_config(filename):try:withopen(filename,r,encodingutf-8)asfile_object:returnjson.load(file_object)exceptFileNotFoundError:return{}defsave_config(filename,config):withopen(filename,w,encodingutf-8)asfile_object:json.dump(config,file_object,ensure_asciiFalse,indent2)这样后面需要读取或保存配置时就不用重复写文件操作代码。初学者容易踩的坑问题常见原因建议文件找不到路径不对或文件不存在检查当前目录和文件名写入后原内容没了使用了w模式想追加用a模式中文乱码没指定编码使用encodingutf-8JSON 读取失败文件内容不是合法 JSON确认文件格式正确捕获异常太宽泛直接写except:尽量捕获明确异常类型工作里能怎么用场景用法读取配置json.load()保存执行结果写入文本或 JSON记录日志追加写入文件输入校验捕获ValueError文件缺失兜底捕获FileNotFoundError示例读取配置并给默认值configload_config(config.json)retry_countconfig.get(retry_count,3)print(retry_count)小结with open()可以安全打开文件read()读取全部内容readlines()读取为列表w模式会覆盖文件a模式会追加内容try-except可以处理运行时错误else适合放没有异常时才执行的代码JSON 适合保存简单结构化数据文件读写逻辑重复时可以重构成函数下一篇下一篇继续讲测试。文件、异常和 JSON 能让脚本更实用测试能帮我们确认代码改动后仍然可靠。