python基础03——文件和异常

目录

文件读写

判断文件结尾

异常

使用 try/except 捕获异常

支持多个except子句

except不指定异常类型

将异常赋给变量

else子句

finally子句


  • 文件读写

file = open('a.txt','w')
file.write('haha')
file.close()

file = open('a.txt','r')
content = file.read()
print(content)
file.close()

open函数创建一个文件对象并将其与磁盘文件关联,第一个参数是文件路径,第二个参数是模式,包括读、写、追加等等,基本和其他语言类似。

文件对象支持用read、readline和write等方法对文件进行读写。用完记住用close方法关闭文件。

  • 判断文件结尾

file = open('haha.txt', 'w')
file.write('line1\n')
file.write('line2\n')
file.write('line3\n')
file.close()

file = open('haha.txt', 'r')
line = file.readline()
while line != '' :
    print(line)
    line = file.readline()

file.close()
file = open('haha.txt', 'r')
for line in file: 
    print(line)

file.close()

readline方法在到达文件末尾时会返回空字符,可以用它作为判断条件。

或者使用for循环会更优雅。

注意,上面打印会多打一个空行,可以使用字符串line的rstrip('\n')方法去掉末尾空行,或者print函数加参数end='',来指示结尾不用加空行。

  • 异常

  • 使用 try/except 捕获异常

try:
    x = 1 / 0
except ZeroDivisionError:
    print("ZeroDivisionEror")

  • 支持多个except子句

try:
    x = int("1 / 0")
except ValueError:
    print("ValueError")
except ZeroDivisionError:
    print("ZeroDivisionEror")

支持多个except子句,分别捕获多个异常

  • except不指定异常类型

try:
    x = 1 / 0
except :
    print("ERROR!")

except不指定异常类型,可以捕获所有异常

  • 将异常赋给变量

try:
    x = 1 / 0
except Exception as e:
    print(f"GOT ERROR: {e}")

可以将异常赋给变量以便输出错误信息,如上面的e。

此时一定要指定异常类型,如果不知道异常类型,就用Exception类型。

  • else子句

try:
    x=int(input("input a integer"))
except:
    print("ERROR: wrong input")
else:
    print(f"your number is {x}")

try/except/else:在所有except子句后可以出现else子句,当try语句没有引发异常时才会执行。

  • finally子句

try:
    file = open('notfound.txt','r')
    for line in file:
        print(line)
except:
    print("open file error!")
finally:
    file.close()

try/except/finally:不管有没有抛出异常,都会执行,用于释放资源等场景。

注:上面写法有问题,如果打开文件时抛异常,则在finally中file变量都不存在。

上一篇:python基础02——函数

下一篇:python基础04——列表和元组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值