I am aware this question is common but no solution has been able to solve my problem yet... I keep getting this error, FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'
when running a simple python script to open a file on an Anaconda Virtual Environment (VSCode) on Mac OSX... I tried doing the import os
and then os.chdir("...")
to change the working directory to get my files to open, but nothing is working.
Asked
Active
Viewed 4,512 times
1
-
Can you show the code and the directory structure so we can get a clearer picture? – Vedang Waradpande Nov 05 '18 at 06:23
-
I simply have a .py file running the code 'inputFile = open("keywords.txt", "r")' in a folder called 'Projects' on my desktop. This same folder holds a .txt file called 'keywords' – CosmicCat Nov 05 '18 at 06:49
-
If the .py file and the .txt file are in the same folder why do you need to use ```os.chdir()```? Also, can you check if you have saved the file with the extension ```'.txt'```? If you have saved it as ```keywords``` and not ```keywords.txt``` the error is expected. In this case try changing the filename to ```keywords.txt``` and see. – Vedang Waradpande Nov 05 '18 at 07:41
-
1Possible duplicate of [Python open() gives IOError: Errno 2 No such file or directory](https://stackoverflow.com/questions/12201928/python-open-gives-ioerror-errno-2-no-such-file-or-directory) – phd Nov 05 '18 at 12:05
-
https://stackoverflow.com/search?q=%5Bpython%5D+No+such+file+or+directory – phd Nov 05 '18 at 12:05
-
I would do `print(os.getcwd())` to make sure you and Python agree on what directory you are working in. Otherwise specify an absolute path to the file. – Brett Cannon Nov 05 '18 at 20:24
-
Everything is in the same folder, and the textfile has the .txt extension but I still get an error when trying to open it on the very first line of my code... what do i do now? – CosmicCat Nov 06 '18 at 00:32
-
The file extension doesn't matter. I would either look at the links phd provided or specify an absolute path to the file. – Brett Cannon Nov 07 '18 at 19:28
2 Answers
0
I had the same issue. I tried just "Copy Relative Path" (right click on *.txt file in the explorer) and paste instead of the *.txt file name, it worked for me.

JorSan
- 65
- 9
-1
save 'file.txt' on the same location where pyhon file are saved by anaconda.it worked for me on windows.read more here.https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files