renaming a layer thats just been created

1588
3
12-20-2011 06:28 AM
OliverMorris
New Contributor III
Hi,

I am creating a layer with python, is there a way of renaming it immediately or a way to identify what layer was just added so I can rename it, see code below:

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
layers = arcpy.mapping.ListLayers(mxd, "", df)
words = ['curpm1', 'curpm2', 'curpm3']
for word in words:
    print word
    groupLayer = arcpy.mapping.Layer(r"C:\Users\oliverm\Desktop\GIS1\GL1.lyr")
    arcpy.mapping.AddLayer(df, groupLayer, "BOTTOM")
    'rename layer here'

Thank you very much for your help, I ideally want to be able to create the newly added layer as one of the list words.

Oliver
Tags (2)
0 Kudos
3 Replies
StephanieWendel
Esri Contributor
You can use the layer Name property as it is read/write for that layer file. This provides the ability to set or get the name of a layer the way it would appear in the ArcMap table of contents. Spaces can be included. All layer types support this property. Check out the layer class page for more information about the name property and the others you can call on a layer.

You will probably want to loop through your layers but then you can use something like this to see the layer name:
for lyr in layers:
    print lyr.name
0 Kudos
StephenLong
New Contributor
The lyr.name = "NewName" seems to work, but the layer is removed from the TOC.
Basic Code below:

# Import arcpy module
import arcpy
   
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyr = arcpy.mapping.ListLayers(mxd)[0]
lyr.name = "NewName"
arcpy.RefreshTOC()

Has anyone else had this problem, and has come up with a solution?
I will note that if you enter these lines directly into the command prompt they work fine, BUT
if you inport the python script into a Toolbox there is a problem with the layer being removed.

Any help would be appreciated.
0 Kudos
JeffBarrette
Esri Regular Contributor
This is a know issue (NIM070882) and will be addressed in SP4.  In the meantime, run your script as a stand-alone script (i.e., not using CURRENT) and it should work fine.

Jeff
0 Kudos