We will learn, with this explanation, how to solve the
No such file or directory error in Python.
Python: can't open file 'setup.py': [Errno 2] No such file or directory Error
We have a simple Python script to open a file, read the contents, and display it, but we are getting this error (
FileNotFoundError). So, we will show you how to solve this error and why this occurs.
Example = open("test.txt", "r") Example = Example.read() print(Example)
PS C:\WINDOWS\System32\WindowsPowerShell\v1.0> python -u "f:\example\python can't open file 'setup.py' [errno 2] no such file or directory\example.py" Traceback (most recent call last): File "f:\example\python can't open file 'setup.py' [errno 2] no such file or directory\example.py", line 1, in <module> Example=open('test.txt','r') FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
The basic reason for this error is that our file is not present in the same location as our Python script. One simple way to solve it is to copy this
test.txt file and paste this file where the Python script is located so that this script will work.
There is another way to solve this error without a copy of this
test.txt in the same folder, but we will need to give the absolute path or complete path where we pass the file name inside the Python script.
Now, we need to go to the folder where our
test.txt file is located and click Navigation. And we will get the location of this folder, copy it, go back to the Python script, and then paste it where we pass the file name.
Example = open(r"C:\Users\Dell\Desktop\test\test.txt", "r") Example = Example.read() print(Example)
We are using
r before the double quotation marks to avoid the escape character, and if we run this Python script, we will not get any error. Instead of getting errors, we get the output.
So this is how we solve this. And if you are still getting this error, you have made silly mistakes in naming the file, so you must ensure your file name is correct.
This approach will work anywhere. For example, if you run the
setup.py file, you have to specify the complete path where this file is located or install any Python package so that you have to access the complete path to the installation.
- Can Only Concatenate List (Not Int) to List in Python
- Invalid Syntax in Python
- Value Error Need More Than One Value to Unpack in Python
- ValueError Arrays Must All Be the Same Length in Python
- Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python