In this article, let us learn what causes FileNotFoundError and see how we can fix that and get our code up and running again!
Troubleshooting any errors will include the following steps
Let us start by understanding the FileNotFoundError and its causes!
Step#1: Understanding FileNotFoundError and its Causes
What Is FileNotFoundError?
A short one line explanation would be
FileNotFoundError is an exception that is raised when Python fails to locate the file mentioned in the code.embeddedinventor.com
But then this much is obvious from the name of the Exception!
Let us see when, why, and how python will fail while locating files and how to actually fix that!
If you are in the first steps of your Python journey and you are not 100% clear about what exceptions are, I strongly recommend reading our article on Exceptions before proceeding with this one!
There we have explained the concept of exceptions from a beginner perspective with the goal that you will leave away with an intuitive feeling on what exceptions actually are and what their place is in the world of programming!
What Causes FileNotFoundError?
Here’s how that would look in action:
In the above example, I tried to open the file named ‘example.txt’.
But python failed to locate the file named “example.txt” and raised the FileNotFoundError.
But then why did it fail?
There are several causes that might lead to failure in locating the module we wished to import, some of them are
- File is not present in your computer
- You have entered the name of the file incorrectly
- File is present, but not in the same directory as python expects
Now that we have learnt all the causes that can lead to FileNotFoundError, we are almost there to get our code up and running again, lets move on to Step#2!
Step#2: Figuring Out the Exact Cause in your situation
The next step is to obviously figure out which of the 3 scenarios caused your issue!
Before getting into that here is a pro tip for you, to fix not just FileNotFoundError but any error in Python. Whenever your program crashes with an Exception, (take a deep breath and) have a look at the huge wall of error text that just got printed on your screen!
There is actually a lot of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!
For visual learners out there we have also made an interesting video on that topic!
Coming back to the topic let us take a closer look at each of these causes so that you can figure out which one of these caused the problem for your particular case!
Cause#1: File Not Present
Let us start with the simplest cause of FileNotFoundError, which is we are trying to open and read a file that does not exist.
You have probably already done this step before reaching this article, just in case you haven’t I highly recommend you double check before reading on!
Fix for Cause#1: Double check and make sure the file is present
Perhaps the file was present the last time you ran the code, and it was moved or deleted in the meantime!
So take a couple of seconds to double check to ensure that the file is still there!
If you wish to automate the process of creating the new file in case it was moved of deleted then you can use the code snippet below!
file_name = "example.txt"
myFile = None
myFile = open(file_name, 'r')
myFile = open(file_name, 'w')
Here we first check if the file is present in the try block and if its not, then we try opening again in “write mode” in the except block, which will create a new file instead!
If the above code feels hazy to you, I highly recommend reading this other on Exceptions before continuing this one!
File is there but the error is also still there? Don’t worry, we will fix it! At least we have eliminated one of the causes in our list!
Cause#2: “Extension” is not included in the file name
Beginners and some time even experienced professionals often fall into this trap and forget that file-name “extensions” like .py or .txt needs to be provided!
For example, here I have created a text file named example.
When I try to open it if I do not mention the file extension correctly I will end up with FileNotFoundError as shown below!
Fix for Cause#2: Include the extension in the file name
If you are not sure what the extension is I suggest going through the steps shown in the screenshot below to make sure extension is visible in the file explorer!
As you can see, now that we know that the file extension is “.txt”, we can include that in our code to fix the issue and make our code run without errors as shown below!
If the extension is already correct, double-check the spelling too!
Spelling and extensions are correct? Then I must say you are a person who pays attention to detail!
Then the cause for your issue is to do something with the folder structure!
The fix for this case is simple! Just make sure you have spelt the module name correctly and used the correct case in your spelling!
You can always google the line “import <module-name>” to figure out the correct way to write the module name!
Cause#3: File Not in the Correct Location
This one is not as simple as the other ones, especially for beginners, but we will get there!
First we need to learn some terminology correctly.
So what do I mean by “correct location“?
What is Current Working Directory?
Directory is just a fancy way of saying “folder”, and the current working directory is the folder in your computer that python is running from.
In other words, all python sees is “one particular folder” and that folder is called the “current working directory”
If you mention just the name of the file, the only place python will look into is the current working directory.
This is usually the directory where your python script (the .py file) is living in, but not necessarily though (more on this later!)
Let us next see what the current working directory is in your particular case, and verify if our “file of interest” is in that same folder or not!
Confirming that your file is in the current working directory
To figure out what directory your file is in, you can simply go to whereever the file you are trying to open is and get the directory from the address bar as shown below!
They in our python script or in the python interpreter, you can figure out what your current working directory is using the following snippet!
current_directory = os.getcwd()
print(current_directory) #OUTPUT C:\workspace\tutorials
Now that we know what the current working directory is, we can verify if the file of interest” and the current working directory are one and the same!
We can also do this via python using the following line of code!
files = os.listdir(current_directory)
print(files) # OUTPUT: ['example.txt', 'fileExamples.py']
This code prints out the names of the files present in the current working directory as shown below
This way you can verify if the file you are trying to open is actually present in the current working directory!
In my case, they file of interest is example.txt and as you can see it is in the current working directory.
If in your case, your file of interest is not present in the output, there are several ways to fix it. I suggest reading through them all and select a suitable fix!
Fix#1: Move the file to the current working directory
This one is simple, simply move the file of interest to the current working directory, and try running your code again and it should now work just fine!
If you are a beginner trying out some code you found online, then this fix might be all that you need!
But again, this is not the way pros do things! Read on to see how to fix it like a pro!
Fix#2: Use Absolute Path
What is absolute path? The absolute path tells you where exactly a given file or folder is on your computers.
In my case the absolute path of the file “example.txt” is
Which tells me that my file is
- in the C: drive
- inside a folder called workspace
- inside a folder called tutorials
- a file named example.txt
So in your code you can do something like
myFile = open("C:\workspace\tutorials\example.txt", "r")
which should work without any errors, even if the file of interest is not in the current working directory! Since now the python interpreter now has more information on exactly where to look for the file!
A good analogy would be, instead of saying
I live in house number is 52
If we say
I live in Country:X, City:Y, Street:Z, House:52
anyone can easily locate you!
There is a pitfall that we need to avoid if we are using this fix!
The “Escape Sequence” Pitfall
If you have tried C programming language before python you would of noticed that the “Enter” or “Return” key of our keyboard can be represented in code using “\n” and “Tab” key can be represented using “\t”
So if your absolutive path contains any of these then it will result in an error as shown below!
myFile = open("C:\workspace\tutorials\next_example.txt", "r")
As you can see we get an “OSError” error instead “FileNotFoundError”!
This is because we have the backslash symbol “\” and the letter “n” next to each other!
In order not to fall into this trap, always prepend the path with the letter “r” as shown below
myFile = open(r"C:\workspace\tutorials\next_example.txt", "r")
Then our code should work just as expected!
Here “r” indicated that it is a “raw string” which basically tells python to ignore any escape sequences!
Fix#3: Use Relative Path
For example, if you wish to tell your classmate where you live, you would say something like
I live in Street:Z, House:52
I live in Country:X, City:Y, Street:Z, House:52
Here the country and the city are same as your classmate’s so there is no need to mention them!
Relative path works the same way, it is relative to the current working directory.
For example if my current working directory’s path is
and the path to my “file of interest” is
Then in my program I can simply write
myFile = open(r"tutorials\example.txt", "r")
and it should work without errors!
If you are file lives one directory “up” lets say in “C:” and your current working directory is “C:\workspace”
Then you can still use relative path like this!
myFile = open(r"..\example.txt", "r")
Here “..\” represents “one directory up”, wanna go 2 directories up? use “..\..\example.txt” instead!
Fix#4: Run python from the same directory as the file
This is an advanced one! (source)
If you are running a python script from the command line, you can make sure that the current working directory of the python script matches the directory your “file of interest” is present in by calling the file using absolute or relative path as shown below!
myFile = open(r"example.txt", "r")
- I have a python file named “fileExamples.py” in the folder “C:\workspace” and
- my file of interest “example.txt” lived in “C:\workspace\tutorials”
So I first changed the current working directory using the “cd” command, into where my “file of interest” was, then I called my python script using the relative path “..\” (which means one-directory up.) and the code worked without errors!
If you don’t feel comfortable with the command line interface, then I suggest watching this video we made on that topic to make the restless felling go away once and for all!
Handling FileNotFoundError if you have No Control Over Paths
In case you have no control over the paths, say for example, you are giving out the code to your friend or client and you have no control over how they will run the file, then the best thing to do is to “gracefully handle” the error, as you can no longer “avoid” it!
To do that place all your open() statements inside the try block, and have a specific except clause to handle the FileNotFoundErrors as shown below
f = open("examplefile.txt", "r")
print("ERROR: Please make sure you follow the README file!")
I would just give out a README.txt file along with the python script, with instructions on how to run your code to the client and print out something like this in case of errors! This way they can try fixing it themselves before coming to me!
This way instead of getting a huge wall of text with no clue how to proceed, the client will have a specific error message and instructions on how to fix the errors!
I hope by now you got the code up and running again!
If so we have reached the end of the road! Don’t forget to celebrate!
For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions in Python!
If you are a visual learner here is a YouTube video that we made on that same topic!
And with that, I end this article.
I hope you enjoyed reading this article and found it useful!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!
Thanks to Namazi Jamal for his contributions in writing this article!