I am trying to reference a Layer named "Tim" in the dataframe "Layers" in my .mxd. It is not working. I have looked at the ArcGIS online help and all else in this forum. Can't get rid of this Runtime Error!
>>> mxd = arcpy.mapping.MapDocument("CURRENT")
>>> df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
>>> layer = arcpy.mapping.ListLayers(mxd,"Tim",df)[0]
Runtime error : list index out of range
Any insight would be greatly appreciated!!
So this is my entire script:
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd, "layers")[0]
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Tim", df)[0]
addLayer = arcpy.mapping.Layer(r"MyLayer.lyr")
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM")
this also give me the error.
When i change
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Tim", df)[0]
to this
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "", df)[0]
it works but i need it do reference a specific group layer because there will be many of them and eventually i will pass in a variable for the targetGroupLayer so i can bring in certain layers into that group.
My most recent as Roy suggested.
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "",df):
if lyr.name == "Tim":
addLayer = arcpy.mapping.Layer(r"C:\Users\T\Desktop\MyLayer.lyr")
arcpy.mapping.AddLayerToGroup(df, lyr, addLayer, "BOTTOM")
No luck still!
Thanks for all the suggestion also!! I will keep trying!
** This script is working now!!* Thanks Roy!
Answer
I've had luck with listing all the layers within a dataframe and checking with a loop as opposed to specifying dirctly in the ListLayers method. Same goes for the data frame.
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, "", df):
if lyr.name == "Tim":
# Do some stuff.
To address your reference to it being in a group, from ESRI Help files:
Group layers are treated just like layers. The index values are simply generated from top to bottom as they appear in the table of contents or the way they would appear in a layer file. The same applies if a group layer is within another group layer. A map document with a single group layer with three layers within it will return a Python list of four layer objects, the group layer being the first. One way of determining if a layer is inside a group layer is to interrogate the longName property. A layer's longName will include the group layer name as part of the name.
No comments:
Post a Comment