[GIS] Using arcpy.mapping to make changes to an open mxd

arcpymxd

I want to use arcpy.mapping to make some changes to a mxd. I am using the Spyder environment for python. To change the title I can use the following code:

import arcpy

myMap = r'C:\path_to_mxd\myfile.mxd'
mxd = arcpy.mapping.MapDocument(myMap)
mxd.relativePaths = True
mxd.title = 'Title'
arcpy.RefreshActiveView()
mxd.save()

I can't execute mxd.save() on an open mxd file though. Is there a way to make changes to an open file and view any code I execute on the fly?

Best Answer

You cannot save an open MXD from a python IDE external to ArcGIS.

You can, however, make changes to and save an MXD using Python from ArcMap itself. Open the python window (or you can attach to a script tool if you prefer) and run your python from inside the open MXD. You can display the python window from the menus Geoprocessing > Python Window.

You need to indicate to arcpy that you are looking at the open MXD by using arcpy.mapping.MapDocument("CURRENT")

mxd = arcpy.mapping.MapDocument("CURRENT")
mxd.relativePaths = True
mxd.title = 'Title'
arcpy.RefreshActiveView()
mxd.save()
Related Question