- Python FileNotFoundError: [Errno 2] No such file or directory Solution
- Python FileNotFoundError: [Errno 2] No such file or directory
- Example FileNotFoundError
- Misspelled file name
- Invalid file path or directory path
- Using a relative path
- Solution to FileNotFoundError: [Errno 2] No such file or directory
- Python file opening error
- # FileNotFoundError: [Errno 2] No such file or directory
- # Move the file to the same directory as your Python script
- # Specifying an absolute path to the file
- # Make sure to use a raw string if the path contains backslashes
- # Using a relative path to open the file
- # Checking if the specified file exists before opening it
- # Creating a file with the specified name if it doesn’t exist
- # Make sure you have specified the correct filename
- # Changing to the directory that contains the file
- # Things to node when debugging
Python FileNotFoundError: [Errno 2] No such file or directory Solution
In Python, when you reference a file, it needs to exist. Otherwise, Python will return a FileNotFoundError: [Errno 2] No such file or directory.
In this tutorial, let’s look at what is FileNotFoundError: [Errno 2] No such file or directory error means and how to solve this in your code.
Python FileNotFoundError: [Errno 2] No such file or directory
Python will raise FileNotFoundError when you use the OS library and try to read a file or write a file that does not exist using an open() statement.
It is, of course, excluding you are creating a new file and writing content to the file. Any error message which states FileNotFoundError means that Python cannot find the path of the file you are referencing.
Example FileNotFoundError
The below code will list all the files in a specified folder. We will be using the OS module and os.listdir() method to get a list of files in the specified folder.
import os for f in os.listdir("/etc"): print(f)
Traceback (most recent call last): File "Main.py", line 2, in for f in os.listdir("/etc/test"): FileNotFoundError: [Errno 2] No such file or directory: '/etc/test'
Now you can see that Python is throwing FileNotFoundError: [Errno 2] No such file or directory since the folder reference is wrong here.
The possible reasons for this error could be as follows.
Misspelled file name
The error will often occur due to misspelled filenames, so providing the correct file name would solve the issue.
Invalid file path or directory path
Sometimes you might give a wrong file path or directory path which does not exist. It usually happens even with the network path when it’s unreachable. So ensure that the file path is correct and if you are placing the file in the network path, make sure it’s reachable and accessible.
Using a relative path
If you use a relative path, the file would be searched in the current working directory and not in the original path. So ensure you give an absolute path of the file to resolve the error.
Solution to FileNotFoundError: [Errno 2] No such file or directory
We will correct our above code by referencing the proper directory where the file exists. This time, we will also use an absolute path instead of a relative path to ensure it’s referencing the correct directory.
import os for f in os.listdir("C:/Projects/Tryouts/etc"): print(f)
python.txt index.md Python Data Science Ebook.pdf
Python file opening error
Last updated: Feb 17, 2023
Reading time · 7 min
# FileNotFoundError: [Errno 2] No such file or directory
The most common causes of the «FileNotFoundError: [Errno 2] No such file or directory» error are:
- Trying to open a file that doesn’t exist in the specified location.
- Misspelling the name of the file or a path component.
- Forgetting to specify the extension of the file. Note that Windows doesn’t display file extensions.
To solve the error, move the file to the directory where the Python script is located if using a local path, or use an absolute path.
Here is an example of how the error occurs.
Copied!# ⛔️ FileNotFoundError: [Errno 2] No such file or directory: 'example-file.txt' with open('example-file.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
We tried to open a file called example-file.txt and it wasn’t found in the specified directory.
This is a relative path, so Python looks for example-file.txt in the same directory as the Python script ( main.py ) in the example.
Copied!# 👇️ relative path (the file has to be in the same directory) example.txt # 👇️ absolute path (Windows) 'C:\Users\Alice\Desktop\my-file.txt' # 👇️ absolute path (macOS or Linux) '/home/alice/Desktop/my-file.txt'
An absolute path is a complete path that points to the file (including the extension).
Note that Windows doesn’t display file extensions.
# Move the file to the same directory as your Python script
One way to solve the error is to move the file to the same directory as the Python script.
You can use the following 3 lines to print the current working directory (of your Python script) if you don’t know it.
Copied!import os current_directory = os.getcwd() # 👇️ /home/borislav/Desktop/bobbyhadz_python print(current_directory)
For example, if you have a Python script called main.py , you would move the example.txt file right next to the main.py file.
Copied!with open('example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
The code sample assumes that you have an example.txt file in the same directory as the main.py file.
# Specifying an absolute path to the file
Alternatively, you can specify an absolute path to the file in the call to the open() function.
An absolute file that points to the file might look something like the following (depending on your operating system).
Copied!# 👇️ on macOS or Linux my_str = r'/home/alice/Desktop/my-file.txt' # 👇️ on Windows my_str_2 = r'C:\Users\Alice\Desktop\my-file.txt'
Here is a complete example that uses an absolute path to open a file.
Copied!absolute_path = r'/home/borislav/Desktop/bobbyhadz_python/example.txt' with open(absolute_path, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
Make sure to specify the entire path to the file, including the extension.
On most operating systems, you can find the absolute path to a file by:
The path that is shown will likely not include the name of the file, but will point to the directory that contains the file.
Make sure to specify the name of the file and the extension at the end.
You can also open the file in finder and look at the path.
# Make sure to use a raw string if the path contains backslashes
If your path contains backslashes, e.g. ‘C:\Users\Alice\Desktop\my-file.txt’ , prefix the string with r to mark it as a raw string.
Copied!my_path = r'C:\Users\Alice\Desktop\my-file.txt'
Backslashes are used as escape characters (e.g. \n or \t ) in Python, so by prefixing the string with an r , we treat backslashes as literal characters.
# Using a relative path to open the file
You can also use a relative path, even if the file is not located in the same directory as your Python script.
Assuming that you have the following folder structure.
Copied!my_project/ main.py nested_folder/ example.txt
You can open the example.txt file from your main.py script as follows.
Copied!with open(r'nested_dir/example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
We first navigate to the nested_dir directory and then open the file.
If your file is located one or more directories up you have to prefix the path with ../ .
For example, assume that you have the following folder structure.
Copied!Desktop/ my_project/ main.py example.txt
To open the example.txt file, navigate one directory up.
Copied!with open(r'../example.txt', 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
The same syntax can be used to open a file that is located two directories up, e.g. ../../example.txt .
# Checking if the specified file exists before opening it
You can use the os module to print the current working directory and its contents.
Copied!import os current_directory = os.getcwd() # 👇️ /home/borislav/Desktop/bobbyhadz_python print(current_directory) contents = os.listdir(current_directory) print(contents) # 👉️ ['main.py', 'example.py', . ] # 👇️ check if file in current directory print('example-file.txt' in contents) # 👉️ False
The os.getcwd method returns a string that represents the current working directory.
The os.listdir method returns a list that contains the names of the entries in the directory of the specified path.
The code sample prints the contents of the current working directory.
If you don’t see the file you are trying to open in the list, you shouldn’t try to open the file with a relative path (e.g. example.txt ).
Instead, you should use an absolute path (e.g. r’C:\Users\Alice\Desktop\my-file.txt’ ).
We used the in operator to check if a file with the specified name exists.
# Creating a file with the specified name if it doesn’t exist
You can use this approach to create a file with the specified name if it doesn’t already exist.
Copied!import os current_directory = os.getcwd() contents = os.listdir(current_directory) filename = 'example.txt' if filename in contents: with open(filename, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines) else: with open(filename, 'w', encoding='utf-8') as my_file: my_file.write('first line' + '\n') my_file.write('second line' + '\n') my_file.write('third line' + '\n')
We used the in operator to check if the file exists.
If it doesn’t exist, the else block runs where we create a file with the same name, adding 3 lines to it.
If you need to create the file name using variables, check out the following article.
# Make sure you have specified the correct filename
Make sure a file with the specified name exists and you haven’t misspelled the file’s name.
The name of the file shouldn’t contain any special characters, e.g. backslashes \ , forward slashes / or spaces.
If you need to generate unique file names, click on the following article.
# Changing to the directory that contains the file
An alternative solution is to change to the directory that contains the file you are trying to open using the os.chdir() method.
Copied!import os dir_containing_file = r'/home/borislav/Desktop/bobbyhadz_python' # 👇️ change to the directory containing the file os.chdir(dir_containing_file) file_name = 'example.txt' with open(file_name, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
The os.chdir method allows us to change the current working directory to the specified path.
Notice that I passed an absolute path to the method.
The example above assumes that there is an example.txt file in the /home/borislav/Desktop/bobbyhadz_python directory.
Once we use the os.chdir() method to change to the directory that contains the file, we can pass the filename directory to the open() function.
# Things to node when debugging
Make sure to specify the extension of the file. Note that Windows doesn’t display file extensions.
If your path contains backslashes, make sure to prefix it with an r to mark it as a raw string.
Copied!my_path = r'C:\Users\Alice\Desktop\my-file.txt' print(my_path) # 👉️ C:\Users\Alice\Desktop\my-file.txt