品易云推流 关闭
文章详情页
文章 > Python基础教程 > python中FileNotFoundError的异常

python中FileNotFoundError的异常

头像

小妮浅浅

2021-05-14 09:55:119125浏览 · 0收藏 · 0评论

1、Python无法读取不存在的文件,因此它引发一个异常:

Traceback (most recent call last):
    File "alice.py", line 3, in <module>
        with open(filename) as f_obj:
FileNotFoundError: [Errno 2] No such file or directory: 'alice.txt'

在上述traceback中,最后一行报告了FileNotFoundError异常,这是Python找不到要打开的文件时创建的异常。在这个示例中,这个错误是函数open()导致的,因此要处理这个错误,必须将try语句放在包含open()的代码行之前:

filename = 'alice.txt'
try:
    with open(filename) as f_obj:
        contents = f_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)

2、try代码块引发FileNotFoundError异常,因此Python找出与该错误匹配的except代码块,并运行其中的代码。最终的结果是显示一条友好的错误消息,而不是traceback:

Sorry, the file alice.txt does not exist.

以上就是python中FileNotFoundError异常的介绍,希望能对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图