I'm trying to add layers to an empty group layer through arcpy in ArcGIS Pro. I've read that creating empty group layers only works by importing a saved template. I'm able to load my template and it appears in the contents pane. But when I try to add a layer I get the following error.
# Import template dir_path = os.path.dirname(os.path.dirname(__file__)) in_path = os.path.join(dir_path, r'templates\group_template.lyrx') groupLayer = arcpy.mp.LayerFile(in_path).listLayers() # Add group layer to map aprx = arcpy.mp.ArcGISProject("CURRENT") aprxMap = aprx.activeMap aprxMap.addLayer(groupLayer, 'TOP') # Get layer to add lyr = [l for l in aprxMap.listLayers() if l.name == 'test'] # Add layer to group aprxMap.addLayerToGroup(groupLayer, lyr) Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\program files\arcgis\pro\Resources\arcpy\arcpy\utils.py", line 191, in fn_ return fn(*args, **kw) File "c:\program files\arcgis\pro\Resources\arcpy\arcpy\_mp.py", line 1317, in addLayerToGroup return convertArcObjectToPythonObject(self._arc_object.addLayerToGroup(*gp_fixargs((target_group_layer, add_layer_or_layerfile, add_position), True))) ValueError: <MappingLayerObject object at 0x0000000044B73770>
If I add the layer with
aprxMap.addLayer(lyr) everything works fine and
groupLayer.isGroupLayer returns True (lyr is a feature layer). Also, I'm able to add the layer by drag and drop, but I don't want to do that, since this code should finally be part of a larger function. I also tried converting the layer to a layer file as proposed in this question Adding feature class to map (within specific group) using ArcPy with ArcGIS Pro?, but I still get the error.
Does anyone know what I'm doing wrong?