This question already has an answer here:
In Python, what commands can I use to find:
- the current directory (where I was in the terminal when I ran the Python script), and
- where the file I am executing is?
This question already has an answer here:
In Python, what commands can I use to find:
For question 1 use
os.getcwd() # get working dir
andos.chdir(r'D:\Steam\steamapps\common') # set working dir
I recommend using
sys.argv[0]
for question 2 becausesys.argv
is immutable and therefore always returns the current file (module object path) and not affected byos.chdir()
. Also you can do like this:but that snippet and
sys.argv[0]
will not work or will work wierd when compiled by PyInstaller because magic properties are not set in__main__
level andsys.argv[0]
is the way your exe was called (means that it becomes affected by the working dir).To Get your working directory in python. You can Use following code:
A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be
In order to see current working directory type following script:
You may find this useful as a reference:
If you're using Python 3.4, there is the brand new higher-level
pathlib
module which allows you to conveniently callpathlib.Path.cwd()
to get aPath
object representing your current working directory, along with many other new features.More info on this new API can be found here.