VOOZH about

URL: https://www.geeksforgeeks.org/python/why-am-i-getting-a-filenotfounderror-in-python/

⇱ How to fix FileNotFoundError in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to fix FileNotFoundError in Python

Last Updated : 28 Apr, 2025

FileNotFoundError is a built-in Python exception that is raised when an operation such as reading, writing or deleting is attempted on a file that does not exist at the specified path. It is a subclass of OSError and commonly occurs when functions like open(), os.remove() and similar file-handling methods are used without first checking if the file is actually present. Example:

Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 1, in <module>
file = open("abc.txt")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'

Solutions

Let’s look at a few simple ways to fix FileNotFoundError and make sure your program keeps running smoothly even if a file is missing.

1. Check if file exits before opening

Python provides the os.path.exists() method from the built-in os module to check whether a file exists at a given path.


Output
Not found!

2. Using try-except block

Try block is a reliable way to handle FileNotFoundError. It lets your program attempt to open the file, and if the file doesn’t exist, the except block gracefully handles the error without crashing the program.


Output
Not found

3. Use absolute file path

Absolute path specify the exact location of the file on your system, removing any ambiguity about where Python should look for it.

4. Create the file if missing

If the file does not exist, using write mode ("w") in Python will automatically create it. This is useful when you want to ensure the file exists, even if it wasn't there before.

Output

👁 Output
abc.txt file
Comment