知行编程网知行编程网  2022-09-07 14:30 知行编程网 隐藏边栏  504 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python中FileNotFoundError的异常的相关知识,包括python中filenotfounderror,以及except python这些编程知识,希望对大家有参考作用。

python中FileNotFoundError的异常

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'

在上面的回溯中,最后一行报告了一个 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 块并运行其中的代码。最终结果是一条友好的错误消息,而不是回溯:

Sorry, the file alice.txt does not exist.

以上就是python中FileNotFoundError异常的介绍,希望能对大家有所帮助。

更多Python学习指路:


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

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享