pathlib
(Python 3.4 and Up)To get the file path of the current Python script:
1 2 3 4 5 | from pathlib import Path script_path = Path( __file__ ).absolute() print( script_path ) |
If you want the path of the directory that the current Python script file is in:
1 2 3 4 5 | from pathlib import Path script_dir = Path( __file__ ).parent.absolute() print( script_dir ) |
os.path
To get the file path of the current Python script:
1 2 3 4 5 | import os script_path = os.path.abspath( __file__ ) print( script_path ) |
If you want the path of the directory that the current Python script file is in:
1 2 3 4 5 | import os script_dir = os.path.abspath( os.path.dirname( __file__ ) ) print( script_dir ) |
__file__
__file__
is an attribute (special variable) set by Python in modules that are loaded from files (usually, but not required to be, files that have the .py
extension). The attribute is not set when you're running code inside a Python shell (the python
or python3
command line program), in a Jupyter notebook, or in other cases where the module is not loaded from a file.
Although we could use __file__
by itself:
print( __file__ )
it is not guaranteed to be an absolute path (i.e., it may be a relative path). The pathlib.Path.absolute()
or os.path.abspath
call ensures that it is an absolute path.
__file__
is always an absolute path "by default, with the sole exception of __main__.__file__
when a script has been executed directly using a relative path." See Other Language Changes — What's New in Python 3.4.