To get the full path to the directory a Python file is contained in, write this in that file:
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
(Note that the incantation above won't work if you've already used to change your current working directory, since the value of the os.chdir() constant is relative to the current working directory and is not changed by an __file__ call.)os.chdir()
To get the current working directory use
import os
cwd = os.getcwd()
Documentation references for the modules, constants and functions used above:
os and os.path modules.__file__ constantos.path.realpath(path) (returns "the canonical path of the specified filename, eliminating any symbolic links encountered in the path")os.path.dirname(path) (returns "the directory name of pathname path")os.getcwd() (returns "a string representing the current working directory")os.chdir(path) ("change the current working directory to path")The special variable contains the path to the current file. From that we can get the directory using either __file__ or the pathlib module.os.path
For the directory of the script being run:
import pathlib
pathlib.Path(__file__).parent.resolve()
For the current working directory:
import pathlib
pathlib.Path().resolve()
For the directory of the script being run:
import os
os.path.dirname(os.path.abspath(__file__))
If you mean the current working directory:
import os
os.path.abspath(os.getcwd())
Note that before and after is two underscores, not just one.file
Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), may not be set since there is no notion of "current file". The above answer assumes the most common scenario of running a python script that is in a file.__file__
os.path.dirname(os.path.abspath(__file__))
is indeed the best you're going to get.
It's unusual to be executing a script with /exec; normally you should be using the module infrastructure to load scripts. If you must use these methods, I suggest setting execfile in the __file__ you pass to the script so it can read that filename.globals
There's no other way to get the filename in execed code: as you note, the CWD may be in a completely different place.