If Python stops with FileNotFoundError, the program is usually not broken. Python is telling you that it looked for a file at a particular location and could not find it there. The confusing part is that the file may be visible in your file manager, while Python still says it does not exist.
This happens most often because the program is using a different working directory than you expect, the filename has a typo, a relative path points somewhere else, or the file is not included in the project. The good news is that the error is easy to diagnose once you inspect the path Python is actually using.
What does FileNotFoundError mean?
Consider this example:Copy
with open("data.csv", "r", encoding="utf-8") as file:
contents = file.read()Python searches for data.csv in the program’s current working directory. If the file is not there, it raises an error similar to this:Copy
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'The important detail is not only the filename. The program’s current location matters too. A relative path such as data.csv does not mean “find this file anywhere on my computer.” It means “find this file inside the directory Python is currently using.”
1. Check the exact filename
Start with the simplest possibility: the name is different from what your code says.
Common mistakes include:
data.csvversusData.csvcustomers.csvversuscustomer.csv.CSVversus.csv- An accidental extra space in the filename
- A file saved as
data.csv.txtby a text editor - A spelling mistake in a folder name
Some operating systems hide file extensions, so a file that appears to be called data.csv may actually be data.csv.txt. Turn on visible file extensions and compare the name character by character.
You can also check whether Python sees the path:Copy
from pathlib import Path
path = Path("data.csv")
print(path.exists())
print(path.resolve())exists() returns True if the path exists. resolve() shows the absolute location Python is checking. This small diagnostic often explains the problem immediately.
2. Print the current working directory
A relative path is interpreted from the current working directory, not necessarily from the folder containing your .py file. Check it with pathlib:Copy
from pathlib import Path
print(Path.cwd())Or use the os module:Copy
import os
print(os.getcwd())Suppose your project looks like this:Copy
project/
├── app.py
└── data/
└── data.csvIf the file is inside the data folder, this code is more accurate:Copy
from pathlib import Path
path = Path("data") / "data.csv"
with path.open("r", encoding="utf-8") as file:
contents = file.read()Avoid guessing where Python is running. Print the directory and build the path deliberately.
3. Use an absolute path for a quick test
An absolute path includes the full location of the file. It can confirm whether the problem is simply the relative path:Copy
from pathlib import Path
path = Path(r"C:\Users\Alex\Documents\project\data.csv")
print(path.exists())On macOS or Linux, it may look like this:Copy
from pathlib import Path
path = Path("/home/alex/project/data.csv")
print(path.exists())The r before a Windows string creates a raw string. Without it, backslashes may be interpreted as escape sequences. For example, \n means a newline in a normal Python string.
Absolute paths are useful for debugging, but they are usually a poor final solution. They work only on your computer and will break when you share the project or deploy it to a server. Once you know the correct location, replace the absolute path with a portable project-relative path.
4. Build paths with pathlib
The pathlib module is the cleanest modern way to work with paths. It handles separators correctly on Windows, macOS, and Linux.Copy
from pathlib import Path
project_folder = Path(__file__).parent
file_path = project_folder / "data" / "data.csv"
with file_path.open("r", encoding="utf-8") as file:
contents = file.read()Path(__file__).parent refers to the directory containing the current Python file. This is more predictable than assuming the terminal was opened in the right location.
For a script in project/app.py, the code above searches in project/data/data.csv, even if you launch the script from another directory.
One limitation is that some interactive environments do not define __file__. In a notebook, use Path.cwd() or provide a project root explicitly.
5. Confirm that the file is included in the project
A file may exist on your computer but not in the project you are running. This is common when:
- You opened the wrong project folder in your editor.
- You cloned a repository without downloading data files.
- A
.gitignorerule excludes the file. - The file exists only in a local development environment.
- A deployment process did not copy the file to the server.
List the directory contents from Python:Copy
from pathlib import Path
for item in Path.cwd().iterdir():
print(item)To inspect the expected data folder:Copy
from pathlib import Path
data_folder = Path("data")
if data_folder.exists():
for item in data_folder.iterdir():
print(item.name)
else:
print("The data folder does not exist")This is more reliable than looking at a different file manager window.
6. Check relative paths in an IDE or notebook
IDEs can use different run configurations. A script may run from the project root in one configuration and from the script folder in another. Jupyter notebooks also use the directory where the notebook server started, which may not be the notebook’s own folder.
Use this diagnostic at the top of the program:Copy
from pathlib import Path
print("Working directory:", Path.cwd())
print("Script directory:", Path(__file__).parent)If you are in a notebook and __file__ causes a NameError, remove that line.
The best long-term approach is to make your project layout and path rules explicit. Keep data in a known folder and construct paths from a known root rather than depending on the launch location.
7. Check permissions and locked files
A permissions problem usually produces PermissionError, but permissions can still be part of a confusing file issue, especially on shared servers or protected folders. Make sure the account running Python can read the directory and file.
For a quick check:Copy
from pathlib import Path
path = Path("data.csv")
print("Exists:", path.exists())
print("Readable:", path.is_file())On a server, check the owner and permissions using the operating system’s tools. Do not solve the problem by making every file world-writable. Grant only the access the application needs.
If another program is generating the file, make sure your Python script does not try to read it before it has finished writing. A missing file can be a timing problem rather than a path problem.
8. Handle missing files clearly
For user-facing applications, replace a raw traceback with a useful message:Copy
from pathlib import Path
path = Path("data.csv")
if not path.is_file():
raise FileNotFoundError(
f"Could not find the input file at: {path.resolve()}"
)
with path.open("r", encoding="utf-8") as file:
data = file.read()You can also provide a fallback or ask the user to choose a file. Avoid silently creating an empty file unless that is genuinely the intended behavior. Silent fallbacks can hide data-loss or configuration problems.
9. Use environment-independent project paths
A robust project might define its folders like this:Copy
from pathlib import Path
ROOT = Path(__file__).resolve().parent
INPUTS = ROOT / "data" / "input"
OUTPUTS = ROOT / "data" / "output"
INPUTS.mkdir(parents=True, exist_ok=True)
OUTPUTS.mkdir(parents=True, exist_ok=True)
input_file = INPUTS / "customers.csv"
output_file = OUTPUTS / "clean_customers.csv"This structure separates input and output data and avoids scattering hard-coded paths throughout the program.
For larger applications, configuration files or environment variables may be better. The principle stays the same: define paths in one place and make failures visible.
A quick troubleshooting checklist
When you see FileNotFoundError, check these items in order:
- Read the exact path in the traceback.
- Print
Path.cwd(). - Print
Path("your-file").resolve(). - Confirm the spelling and extension.
- Check whether the file is in the project folder.
- Use
pathlibinstead of manually joining strings. - Confirm your IDE or notebook’s working directory.
- Check deployment, permissions, and file-generation timing.
- Add a clear validation message before opening the file.
Final takeaway
Most Python FileNotFoundError problems come from path assumptions. The fastest fix is to inspect the path Python is actually using, then replace fragile relative strings with clear pathlib objects. Use absolute paths temporarily to diagnose the issue, but build your final solution around project-relative paths so it works when the project moves to another computer or server.