3

I can't remove item from the legend (lyr called "atikot") using arcpy with this code:

import arcpy
from arcpy import env

removeLyr = arcpy.mapping.ListLayers(mxd, "atikot")[0]
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
legend = arcpy.mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT")[0]
for lyr in legend.listLegendItemLayers():
    if lyr.name == "atikot":
        legend.removeItem(lyr)
del mxd

The code does not work. Does anyone have an idea as to what's wrong with the code?

5

I think the problem with your code is that you have not included an mxd.save() before deleting your map document (mxd) object at the end. You're also referring to your mxd variable before you have assigned it.

Your modified code should look like this:

import arcpy
from arcpy import env

mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
legend = arcpy.mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT")[0]
for lyr in legend.listLegendItemLayers():
    if lyr.name == "atikot":
        legend.removeItem(lyr)
mxd.save()
del mxd

Make sure that you save the map document (mxd) object before you delete it.

0

Eventually, I tried to remove item from legend on a several mxd's and this is the resulting code:

import arcpy
import arcpy.mapping
import os
import sys
from arcpy import env
import string


env.workspace = r"C:\Project"
for mxdname in arcpy.ListFiles("*.mxd"):
    print mxdname
    mxd = arcpy.mapping.MapDocument(r"C:\Project\\" + mxdname)
    legend = arcpy.mapping.ListLayoutElements(mxd,"LEGEND_ELEMENT")[0]
    for lyr in legend.listLegendItemLayers():
        if lyr.name == "atikot":
            legend.removeItem(lyr)
            print 'remove'
    mxd.save()
del mxd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.