成都网站建设设计

将想法与焦点和您一起共享

创新互联Python教程:python中FileNotFoundError的异常

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电脑。


本文标题:创新互联Python教程:python中FileNotFoundError的异常
路径分享:http://chengdu.cdxwcx.cn/article/dhhgcgp.html