Open In App

How to fix FileNotFoundError in Python

In this article, we are going to cover topics related to ‘FileNotFoundError’ and what the error means. the reason for the occurrence of this error and how can we handle this error.

What is ‘FileNotFoundError’ in Python

FileNotFoundError is an exception in Python that is raised when a program tries to access a file that doesn’t exist. This error typically occurs when you attempt to perform file operations like opening, reading, writing, or deleting a file. Python cannot find the specified file at the provided path or location.



Problem: Here’s an example of how you might encounter a ‘FileNotFoundError’. Here open() function is used to open the file.




file1 = open("abc.txt")

Output



---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-1-e02672f25e85> in <cell line: 1>()
----> 1 file1 = open("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

Solution

Methods to avoid FileNotFoundError Exception

Example: In this example, we are trying to open the file ‘abc.txt’ which is present inside the ‘Myfolder’




file1 = open("sample_data/Myfolder/abc.txt")
print(file1.read())

Output:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi
ut aliquip ex ea commodo consequat. Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.

Handling FileNotFoundError Exception

‘FileNotFoundError’ is a checked exception in Python and exception handling should be done by making use of ‘try’ and ‘except’ block.

Example: Here we have used try and except block to handle the error.




try:
    file1 = open("Myfolder/abc.txt")
 
except:
    print("file not found")

Output

file not found


Article Tags :