python中FileNotFoundError的异常

418次阅读
没有评论

python中FileNotFoundError的异常

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)

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

Sorry, the file alice.txt does not exist.

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

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-03发表,共计699字。
新手QQ群:570568346,欢迎进群讨论 Python51学习