Python文件操作与异常处理这篇整理文件读写和异常处理两个知识点。文件操作在实际项目中几乎天天用异常处理则是让程序更健壮的关键。十九、文件操作一、文件操作的基本流程文件操作就三步打开 - 读写 - 关闭# 1. 打开文件fopen(文件名,访问模式,encoding编码)# 2. 读取或者写入内容contentf.read()# 3. 关闭文件f.close()更好的写法是用with语句自动关闭文件withopen(文件名,r,encodingutf-8)asf:contentf.read()print(content)# 出了with块文件自动关闭二、打开文件 open()文件对象open(文件名,访问模式,encoding编码)文件路径绝对路径从根目录开始完整唯一的路径在哪运行代码都不会出错相对路径以当前代码所在目录为起点只写相对路径.当前目录..上一级目录../..上两级目录访问模式模式含义文件不存在时文件存在时读写位置“r”只读默认报错从开头读文件开头“w”只写创建新文件清空原内容文件开头“a”追加写创建新文件保留原内容文件末尾“r”读写报错从开头读写文件开头“w”读写创建新文件清空原内容文件开头“a”读写追加创建新文件保留原内容文件末尾以上模式默认以文本方式处理文件。后面加b表示二进制模式如rb、wb适用于图片、视频、音频等。二进制模式不需要encoding参数。三、读取文件内容1. read() —— 读取整个文件withopen(test.txt,r,encodingutf-8)asf:contentf.read()print(content)2. read(n) —— 读取n个字符withopen(test.txt,r,encodingutf-8)asf:contentf.read(10)# 读取前10个字符print(content)3. readline() —— 读取一行withopen(test.txt,r,encodingutf-8)asf:linef.readline()# 读取第一行print(line)4. readlines() —— 读取所有行返回列表withopen(test.txt,r,encodingutf-8)asf:linesf.readlines()print(lines)# [第一行\n, 第二行\n, ...]5. 直接遍历文件对象推荐withopen(test.txt,r,encodingutf-8)asf:forlineinf:print(line,end)四、写入文件内容1. write() —— 写入字符串withopen(test.txt,w,encodingutf-8)asf:f.write(hello world!\n)f.write(这是第二行\n)2. writelines() —— 写入字符串列表注意writelines()不会自动添加换行符需要手动在每个字符串末尾加\n。lines[第一行\n,第二行\n,第三行\n]withopen(test.txt,w,encodingutf-8)asf:f.writelines(lines)3. 追加写入withopen(test.txt,a,encodingutf-8)asf:f.write(追加的内容\n)二十、异常一、什么是异常异常Exception是程序在运行过程中发生的错误它会中断程序的正常执行流程。比如除零错误、文件不存在、索引越界等等。二、为什么要处理异常不处理异常程序直接崩溃用户体验差处理异常让程序能够容错在出现错误时走备选方案或给出友好提示不会意外崩溃三、基本的异常处理语法1. try-except捕获常规异常try:# 可能出错的代码result10/0except:# 如果出错执行这里的代码print(出现了异常)2. 捕获指定类型的异常try:numberint(input(请输入数字))result100/numberprint(f结果是{result})exceptZeroDivisionError:print(不能输入0)exceptValueError:print(必须输入数字)3. 捕获异常对象try:my_list[1,2,3]print(my_list[10])exceptIndexErrorase:print(f越界错误{e})4. 一个except捕获多种异常try:# 可能出错的代码passexcept(ValueError,TypeError,ZeroDivisionError)ase:print(f出错了{e})5. 捕获所有异常try:print(num)exceptExceptionase:print(f发生错误{e})6. else —— 没有异常时执行try:result10/2exceptExceptionase:print(e)else:print(没有异常结果是,result)7. finally —— 无论是否异常都执行try:fopen(test.txt,r)exceptExceptionase:fopen(test.txt,w)else:print(没有异常真开心)finally:f.close()# 不管有没有异常文件都会被关闭实际场景读取配置文件如果文件不存在就创建默认配置importjsondefload_config():try:withopen(config.json,r,encodingutf-8)asf:returnjson.load(f)exceptFileNotFoundError:print(配置文件不存在创建默认配置)return{theme:light,lang:zh}exceptjson.JSONDecodeError:print(配置文件格式错误)return{theme:light,lang:zh}configload_config()print(config)文件操作和异常处理就先到这下一篇讲模块、JSON和面向对象。
阅读完成 · 觉得有帮助?