3

I am trying to copy a layer in an mxd and add that layer to the bottom of the TOC using Python, but I have not found a way to save the mxd programatically without making a copy. I also haven't found how to rename the copied layer. Here is my code: it runs with no errors but the copied layer is not added to the mxd when I open it.

import arcpy
import arcpy.mapping


mxd = arcpy.mapping.MapDocument(r"D:/arcgisserver/directories/my_mxd.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
print "df : " + df.name
addLayer = arcpy.mapping.ListLayers(mxd, "", df)[0]
print "layer ? : " + addLayer.name

arcpy.mapping.AddLayer(df, addLayer, "BOTTOM")

# Refresh things
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, addLayer
2
  • 1
    just a little note, if you import arcpy, you need not import arcpy.mapping as well.
    – mr.adam
    Commented Mar 11, 2015 at 16:29
  • Yes I know, you're right, I was just being over-thorough and cut and pasting from a couple different examples.
    – JasonBK
    Commented Mar 11, 2015 at 16:35

1 Answer 1

2

After adding the layer to the in-memory mxd, you should save the mxd using:

mxd.save()

or

mxd.saveACopy (r"D:/arcgisserver/directories/my_mxd2.mxd")

to change the layer name, simply change the name property of the layer:

addLayer.name = "NewLayerName"

Update: To rename the newly added layer you should make a reference to the layer first:

allLayers= arcpy.mapping.ListLayers(mxd, "", df)
copiedLayer = allLayers[len(allLayers)-1]  //because it is added to the bottom of TOC
copiedLayer.name = "NewLayerName"
3
  • simple enough, thanks! one question though: when I use rename in the way you posted, both the original layer and the new copied layer are renamed. How can I rename just the copied layer?
    – JasonBK
    Commented Mar 11, 2015 at 16:42
  • 1
    See the update answer Commented Mar 11, 2015 at 17:06
  • I was just trying something along those lines..works, thanks!
    – JasonBK
    Commented Mar 11, 2015 at 17:14

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.