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 示例

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐