Wednesday 3 June 2015

arcgis 10.1 - Creating empty group layer within existing group layer using arcpy.mapping?


Referencing this question, Adding new group layer with ArcPy?, I'm trying to use python to add a empty group within a group layer. So far I'm able to add a empty group within the map document, however I'm getting an error when trying to add another empty group within the existing group layer. Here is the error message:



Runtime error Traceback (most recent call last): File "", line 1, in File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\utils.py", line 181, in fn_ return fn(*args, **kw) File "c:\program files (x86)\arcgis\desktop10.1\arcpy\arcpy\mapping.py", line 88, in AddLayerToGroup assert isinstance(target_group_layer, Layer) and target_group_layer._arc_object.isGroupLayer AssertionError



Here is my code:


        mxd = arcpy.mapping.MapDocument(r"C:\Temp\test.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
groupLayer = arcpy.mapping.Layer(r"C:\Temp\Group.lyr")

arcpy.mapping.AddLayer(df, groupLayer, "BOTTOM")
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Group", df)
addLayer = arcpy.mapping.Layer(r"C:\Temp\Group2.lyr")
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM") # error here
mxd.save()
del mxd,df

Can you add empty group layers within an existing group (using v10.1 SP1)? The ESRI documentation (see image below) states that you can add .lyr to groups (maybe not a .lyr group layer?).


enter image description here





Here is the working code (thanks to Jason Scheirer):


    mxd = arcpy.mapping.MapDocument(r"C:\Temp\test.mxd")
df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
groupLayer = arcpy.mapping.Layer(r"C:\Temp\Group.lyr")
arcpy.mapping.AddLayer(df, groupLayer, "BOTTOM")
targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Group", df)[0]
addLayer = arcpy.mapping.Layer(r"C:\Temp\Group2.lyr")
arcpy.mapping.AddLayerToGroup(df, targetGroupLayer, addLayer, "BOTTOM")
mxd.save()
del mxd,df


Answer



Typo in your code. Should be:


targetGroupLayer = arcpy.mapping.ListLayers(mxd, "Group", df)[0]

otherwise targetGroupLayer is a list.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...