[GIS] Changing the name of layer using python

arcmaparcpylayers

I am attempting to change the name of the layer. The following code changes the name of the layer but then removes the layer from the map, and I am not sure why.

Note: I don't have any remove layer statements.

for lyrs in arcpy.mapping.ListLayers(mxd, "*", df):
    if lyrs.name == "project_ws":
        lyrs.name = "project_prow"

arcpy.RefreshTOC()
arcpy.RefreshActiveView()

Best Answer

You appear to be doing this in a geoprocessing tool. GP tools try to protect the TOC from manipulation (such as suppressing the outputs of tools called within tools from going to the TOC), so you're going to need to tell it explicitly that you mean to keep this layer around. "But I haven't added a layer!" -- it goes by name, not by reference, so as far as it's concerned "project_prow" is some new rogue layer.

Make a new output parameter of type Feature Layer, and use SetParameterAsText to set its value to the lyrs.name.