I would like to see what is the best way to determine the current script directory in Python.
I discovered that, due to the many ways of calling Python code, it is ha
.py scripts as well as interactive usage:I frequently use the directory of my scripts (for accessing files stored along side them), but I also frequently run these scripts in an interactive shell for debugging purposes. I define __dirpath__ as:
.py file, the file's base directory. This is always the correct path..ipyn notebook, the current working directory. This is always the correct path, since Jupyter sets the working directory as the .ipynb base directory.from pathlib import Path
__dirpath__ = Path(globals().get("__file__", "./_")).absolute().parent
import os
__dirpath__ = os.path.dirname(os.path.abspath(globals().get("__file__", "./_")))
globals() returns all the global variables as a dictionary..get("__file__", "./_") returns the value from the key "__file__" if it exists in globals(), otherwise it returns the provided default value "./_".__file__ (or "./_") into an absolute filepath, and then returns the filepath's base directory.