Often we have scripts that require a home folder location for the script to locate related files -- for example, layer files, data distributed with the tool that it uses, etc. Here are some methods to find that location.
os.path.dirname(sys.argv[0]) or os.path.dirname(__file__)
.
Both these locations find the path of the currently running Python script file.
Usually, __file__
is the best choice.
See: Difference between __file__ and sys.argv[0] (StackOverflow)
Toolbox (.tbx) validation code
In .tbx script tool validation code, sys.argv[0]
returns an empty string, but __file__
will be the path to the function packed in a string like this: u'C:\\test\\Toolbox.tbx#Script_z.InitializeParameters.py'
In this case, the location of the tbx would be: os.path.dirname(__file__)
ModelBuilder tbx location
The ModelBuilder tbx location can be found using os.path.realpath and the Calculate Value tool with this code block:
import os
def home():
return os.path.realpath(".")
Map document location ("Home folder" in ArcMap or Pro)
Some script tools (always run from ArcMap or Pro) may need to locate data relative to the .mxd or .aprx location:
here = os.path.dirname(arcpy.mapping.MapDocument("CURRENT").filePath)
here = arcpy.mp.ArcGISProject("CURRENT").filePath