ArcPy – Accessing Home Directory in ArcMap

arcpypython-2.7workspace

I want to access to a directory and set that as a arcpy.env.workspace in my Python Script Tool. However, this workspace depends on users so I cannot just use my own folders.

Is there a way to access Home directory (where .mxd file is saved) in arcpy?

I tried retrieving the directory from os.getcwd but that refers to "c:\windows\system32" where ArcMap is accessing.

Best Answer

To get the folder that the currently open MXD is in you can use arcpy.mapping.MapDocument('CURRENT').filePath, this returns '' (an empty string) if the MXD isn't saved and the full path to the current MXD if it is saved.

Using the os.path module you can find the folder the document is in with os.path.dirname, thus os.path.dirname( arcpy.mapping.MapDocument('CURRENT').filePath ) is the folder that the current MXD is saved in. Be sure to import os before attempting to use it.

In ArcGIS Pro the object for the current document is arcpy.mp.ArcGISProject, from the examples, the syntax would be os.path.dirname( arcpy.mp.ArcGISProject("CURRENT").filePath ).

Related Question