$ pip install locate
>>> from locate import this_dir
>>> print(this_dir())
C:/Users/simon
.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.