Home » Python

Python | Example of FileNotFoundError

In this tutorial, we are going to learn how to catch the exception FileNotFoundError if file does not exist in the memory?
Submitted by IncludeHelp, on December 30, 2018

Python FileNotFoundError

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

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

Example 1 (FileNotFoundError exception):

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.

# 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):

Here, I am just writing "fopen" instead of "open" which is an error in python because there is no such function named "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





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.