Last modified: Feb 06, 2026 By Alexander Williams
Fix Python File Not Found Error Guide
You run your Python script. An error appears. It says FileNotFoundError. This is a common issue for beginners. Do not worry. This guide will help you fix it.
We will explore why this error happens. You will learn how to check your file path. We will cover absolute and relative paths. You will see practical code examples. By the end, you will solve this error with confidence.
What is a FileNotFoundError?
Python raises a FileNotFoundError when it cannot find a file. You try to open or read a file. The path you provided is wrong. The file does not exist there. Python stops and shows this error.
It often happens with functions like open(). The error message shows the problematic path. Your job is to find why the path is incorrect.
# Example causing FileNotFoundError
try:
file = open('my_data.txt', 'r')
except FileNotFoundError as e:
print(f"Error: {e}")
Error: [Errno 2] No such file or directory: 'my_data.txt'
Main Causes of the Error
Understanding the cause is the first step to a fix. Here are the most common reasons.
1. Typo in Filename or Path
The simplest cause is a spelling mistake. Did you write 'data.txt' instead of 'data.txt'? Check your filename and folder names carefully. Capital letters matter on some systems.
2. Wrong Working Directory
Python looks for files relative to its current working directory. This is the folder your script runs from. It might not be the folder where your script is saved. This is a major source of confusion.
You can check the current directory with Python. Use the os.getcwd() function. Compare it to where your file actually is. For more on running scripts, see our guide on how to run Python file in terminal.
import os
# Print the current working directory
print("Current Working Directory:", os.getcwd())
3. Using Relative Paths Incorrectly
A relative path is based on the current directory. './data.txt' means 'data.txt' in the current folder. '../data.txt' means 'data.txt' in the parent folder. If your relative path is wrong, the file won't be found.
4. File Does Not Exist
Perhaps you never created the file. Maybe it was deleted or moved. Always verify the file exists in the location you expect. You might need to create the file first.
How to Diagnose the Problem
Follow this checklist when you see the error.
Step 1: Check the error message. It shows the exact path Python tried to use.
Step 2: Verify the file exists. Go to your file explorer. Navigate to the path from the error. Can you see the file?
Step 3: Check your current directory. Use os.getcwd() in your script. Is this the folder containing your file?
Step 4: Examine your path string. Look for typos, wrong slashes (/ vs \), or incorrect relative navigation (like too many '..').
Solutions to Fix FileNotFoundError
Here are proven ways to solve the error. Try them one by one.
Solution 1: Use the Full Absolute Path
An absolute path starts from the root of your drive. It is the complete address. This removes confusion about the working directory.
# Using an absolute path (Example for Windows)
file_path = 'C:/Users/YourName/projects/data.txt'
# Or for Mac/Linux
# file_path = '/home/username/projects/data.txt'
try:
with open(file_path, 'r') as file:
content = file.read()
print("File read successfully!")
except FileNotFoundError:
print("File not found. Check the absolute path.")
Drawback: The path is specific to your machine. It will break if you move the file or share the code.
Solution 2: Correct Your Relative Path
Make sure your relative path is correct relative to the script's working directory. A good practice is to base paths on the script's own location.
Use the special __file__ variable. It holds the path to the current script file.
import os
# Get the directory where this script is located
script_dir = os.path.dirname(__file__)
# Create a path to a file in the same directory
file_path = os.path.join(script_dir, 'my_data.txt')
print(f"Looking for file at: {file_path}")
try:
with open(file_path, 'r') as file:
print("File found and opened!")
except FileNotFoundError:
print("File not found in the script's directory.")
This method is robust. It works even if you run the script from a different terminal folder.
Solution 3: Change the Working Directory
You can change Python's current working directory. Use the os.chdir() function. Point it to the folder containing your file.
import os
# Path to the directory containing your data file
target_dir = '/path/to/your/data/folder'
# Change the current working directory
os.chdir(target_dir)
# Now a relative path will work
try:
with open('data.txt', 'r') as file:
print("Success!")
except FileNotFoundError:
print("File not found even after chdir.")
Use this method carefully. Changing the global working directory can affect other parts of your code.
Solution 4: Check File Permissions
On some systems, the file might exist but you lack read permission. This can cause a similar error. Ensure you have the right to access the file.
Best Practices to Avoid the Error
Follow these tips to prevent FileNotFoundError in the future.
Use os.path.join(): This function creates paths correctly for your operating system. It handles slashes automatically.
Verify paths before use: Use os.path.exists() to check if a file or folder exists. It's a safe way to test.
import os
file_path = 'my_data.txt'
if os.path.exists(file_path):
print("File exists. Proceeding to open...")
with open(file_path, 'r') as file:
# Process file
pass
else:
print(f"Warning: The file '{file_path}' was not found.")
Structure your project clearly: Keep all data files in a specific folder like 'data/'. Use relative paths from your script to this folder.
Use try-except blocks: Always handle the possibility of a missing file gracefully. Inform the user instead of crashing.
Conclusion
The Python FileNotFoundError is a common beginner hurdle. It usually means a simple path mistake. The key is to understand how Python locates files.
Start by checking the error message and your current directory. Use absolute paths for quick tests. For portable code, use os.path.join() with __file__ to build robust relative paths.
Always verify a file exists before trying to open it. Use try-except to handle errors cleanly. With these techniques, you will master file handling in Python. Your scripts will be more reliable and easier to share.