python 示例_Python | FileNotFoundError的示例

本文介绍了Python中的FileNotFoundError异常,当尝试访问不存在的文件时会出现此异常。通过示例1和示例2,展示了如何使用try语句来捕获并处理这种异常。
摘要由CSDN通过智能技术生成

python 示例

Python FileNotFoundError (Python FileNotFoundError )

"FileNotFoundError" - This is an exception in python and it comes when a file does not exist and we want to use it.

“ FileNotFoundError” -这是python中的一个例外,当文件不存在并且我们要使用它时出现。

So in the below example, we will learn how to use and handle "FileNotFoundError"? Here, we are writing the code within with try statement.

因此,在下面的示例中,我们将学习如何使用和处理“ FileNotFoundError” ? 在这里,我们使用try语句编写代码。

Example 1 (FileNotFoundError exception):

示例1(FileNotFoundError异常):

Here, we are trying to open a file named "myfile.txt" which does not exist in the memory and handling the exception by using its name.

在这里,我们试图打开一个名为“ myfile.txt”的文件,该文件在内存中不存在,并通过使用其名称来处理异常。

# trying to open a file, which does not exist
try:
    #trying to open a file in read mode
    fo = open("myfile.txt","rt")
    print("File opened")
except FileNotFoundError:
    print("File does not exist")
except:
    print("Other error")

Output

输出量

File does not exist	

Example 2 (Other exception):

示例2(其他异常):

Here, I am just writing "fopen" instead of "open" which is an error in python because there is no such function named "fopen".

在这里,我只是写“ fopen”而不是“ open” ,这在python中是一个错误,因为没有这样的名为“ fopen”的函数。

# trying to open a file, which does not exist
try:
    #trying to open a file in read mode
    fo = fopen("myfile.txt","rt")
    print("File opened")
except FileNotFoundError:
    print("File does not exist")
except:
    print("Other error")

Output

输出量

Other error


翻译自: https://www.includehelp.com/python/FileNotFoundError.aspx

python 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值