python中FileNotFoundError的异常

2025-12-01 0 72,487

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

Traceback (most recent call last):
    File "alice.py", line 3, in 
        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电脑。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 python中FileNotFoundError的异常 https://www.zhiup.top/2145.html

相关