Reputation: 622
So I have been trying to open very basic files like this: inputFile = open("keywords.txt", "r")
But I get this error:
FileNotFoundError: [Errno 2] No such file or directory: 'keywords.txt'
This must be because Python's default working directory is not the one where my .py file is (correct me if i'm wrong). How can I find the exact path of the directory I'm working in and then change Python's default working directory to it?
Note: I'm on OSX Mojave using VSCode and Anaconda (Python 3.6)
Upvotes: 5
Views: 6510
Reputation: 5797
We have to distinguish the two notions: the "working directory
" and the "python environment
".
When you go into VS code
from Anaconda
, then you are in an Anaconda virtual python environment
and it's default directory
.
You can test it with upon-left first icon - "Explorer".
Here you will find a directory structure, where your .py
file actually is.
But sometimes the file what the .py
searching for could be in some quite other directory. If you want to run a python program with some additional files stored in a common directory, then I prefer to use some variable to set the working directory:
work_dir = "path/to/working_directory"
The use
import os
path = os.join(work_dir, somefile.txt)
If the files the python program uses are in a complex directory structure, then changing the working directory won't be a solution. Though when the programmer uses relative paths, it can be.
In VS Code has a terminal where you can check the current Anaconda environment and directory in a bash shell manner.
When you run the program you will see what environment and options your .py
file is actually running in and with.
Upvotes: 2
Reputation: 1117
By default Python's "current working directory" is the folder which it is placed in. Though this might be different when using Anaconda
This will print your current directory
import os
print(os.getcwd())
This will change your directory
os.chdir('Your new file path here')
Then do another print(os.getcwd())
to make sure it worked
Upvotes: -1