2

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.

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Feb 21, 2019 at 2:12
4
  • 1
    Try os.environ.get('USERPROFILE') to get to C:\Users\<username> folder then append 'my documents' to get to the users' documents folder. Caveat: this only works on Microsoft Windows OS. Commented Feb 21, 2019 at 2:19
  • Thanks, but I think this won't work if the project file is saved on other disk drive. Or perhaps I can force the user to use it on C drive. I will also check what os module can do. I am thinking that if ArcMap can make that access there would be a way to do so in arcpy as well. Commented Feb 21, 2019 at 2:27
  • Are you trying to get to the path that the open MXD is saved in? That is arcpy.mapping.MapDocument('CURRENT').filePath for the MXD file and os.path.dirname(arcpy.mapping.MapDocument('CURRENT').filePath) for the folder the MXD is in (returns '' if the MXD isn't saved).There is only one home which should be in the path os.path.join(os.environ.get('USERPROFILE'),r'Documents\ArcGIS') Commented Feb 21, 2019 at 2:48
  • Thank you very much! That is what I am expected. Commented Feb 21, 2019 at 2:56

1 Answer 1

5

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 ).

answered Feb 21, 2019 at 3:42

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.