4

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!

0

1 Answer 1

6

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.

0

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.