Select to view content in your preferred language

Arcpy changing current working directory

9878
5
05-14-2013 06:07 AM
GrzegorzDabkowski
Emerging Contributor
I can't seem to understand the following behaviour:

mxd = ur'G:\MapImageCreator\ImageTaker.mxd'

print os.getcwd()                          # C:\Documents and Settings\dabkowsk\Desktop (where I run the script from)
mxd = arcpy.mapping.MapDocument(mxd)
print os.getcwd()                          # G:\MapImageCreator


Why does creating a MapDocument object change my working directory? This way I can't use any relative path in my entire script. For example, if I describe an output file as just 'abcdefg.txt', it gets created in the mxd's directory, not in the one I run the script from.
Tags (2)
0 Kudos
5 Replies
DuncanHornby
MVP Notable Contributor
Not sure why that would happen, I guess its just defaulting to somewhere as the workspace has not been set.

You set the workspace with the following code

arcpy.env.workspace = r"C:\temp"
0 Kudos
GrzegorzDabkowski
Emerging Contributor
Setting arcpy.env.workspace will not affect my text file creation, will it? Would it affect the other step, creation of a MapDocument? Would it prevent the current working directory from changing? I'll certainly try. But even if it's defaulting, why is that affecting the global cwd, not the arcpy-specific path? I checked the state of arcpy.env.workspace too, it remains None throughout the execution of the code above.
0 Kudos
GrzegorzDabkowski
Emerging Contributor
I added a line setting arcpy.env.workspace, but that didn't change anything.
0 Kudos
GrzegorzDabkowski
Emerging Contributor
To wrap this up, documentation says as follows:

You cannot type relative paths (using the dot and double-dot notation) in any ArcGIS application. Nor can you use relative paths in Python scripts.


I decided to explicitly transform all input relative paths to absolute ones at the beginning of the script, before any arcpy method uses them. It's certainly not convenient not to be able to use relative paths, especially if some interactive use is envisaged, but it seems that's just a limitation of the environment.
0 Kudos
markdenil
Frequent Contributor
relying on environment settings that can change unexpectedly is not a safe practice.
If you can get the path parameters set as you need at the outset,
you can then capture the paths to variables and use the variables to give explicit paths.

That way, Arc and the system can switch between 'current' directories all day, but you have already
captured the locations for later use

for example:
scriptHome = os.getcwd()
0 Kudos