A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/why-am-i-getting-a-filenotfounderror-in-python/ below:

How to fix FileNotFoundError in Python

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:

Python

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.

Python
import os
fp = "abc.txt" 

if os.path.exists(fp):
    with open(fp, "r") as f:
        data = f.read()
else:
    print("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.

Python
try:
    with open("abc.txt", "r") as file:
        data = file.read()
except FileNotFoundError:
    print("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.

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()
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.

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

Output

abc.txt file

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4