Sat Apr 30 2022·2 min read
Photo by Pars Sahin
The Python "FileNotFoundError: [Errno 2] No such file or directory" occurs when we try to open a file that doesn't exist in the specified location. 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.
# ⛔️ 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
example-file.txtin the same directory as the Python script (
main.py) in the example.
One way to solve the error is to move the file to the same directory as the Python script.
Alternatively, you can specify an absolute path to the file in the call to the
An absolute file that points to the file might look something like the following (depending on your operating system).
my_str = r'/home/alice/Desktop/my-file.txt' 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.
my_absolute_path = r'/home/alice/Desktop/my-file.txt' with open(my_absolute_path, 'r', encoding='utf-8') as f: lines = f.readlines() print(lines)
You can use the
os module to print the current working directory and its
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.
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.
An alternative solution is to change to the directory that contains the file you
are trying to open using the
import os dir_containing_file = r'/home/borislav/Desktop/bobbyhadz_python' # 👇️ change to directory containing 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