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 <type 'exceptions.IndexError'>: list index out of range
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!