Open In App

How to fix FileNotFoundError in Python

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

[GFGTABS]
Python

file = open("abc.txt")


[/GFGTABS]

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.

[GFGTABS]
Python

import os
fp = "abc.txt" 

if os.path.exists(fp):
    with open(fp, "r") as f:
        data = f.read()
else:
    print("Not found!")


[/GFGTABS]

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.

[GFGTABS]
Python

try:
    with open("abc.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("Not found")


[/GFGTABS]

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.

[GFGTABS]
Python

import os

print("Current directory:", os.getcwd())
fp = "/absolute/path/to/abc.txt" # file path 

with open(fp, "r") as file:
    data = file.read()


[/GFGTABS]

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.

[GFGTABS]
Python

with open("abc.txt", "w") as file:
    file.write("This file has been created!")


[/GFGTABS]

Output

Output

abc.txt file



Next Article

Similar Reads