correaj

ArcPy will not officially adequately remove my layers when asked

Discussion created by correaj on Dec 24, 2013
Latest reply on Dec 24, 2013 by correaj
I have an mxd which uses data driven pages. I need to iterate through each index page, create a layer from the indexed feature and then select points that intersect it. I haven't reached the last part because I'm having issues deleting the newly created feature layer. The algorithm written in the function "remove_selected_township()" is not finding the layer I create in select_current_township which uses arcpy.MakeFeatureLayer_management to select and create a new feature layer. No matter where I place the function, I will always get this error!
ERROR 000725: Output Layer: Dataset selected already exists.

Maybe I'm not referencing something correctly but does anyone have a good idea?

Your help would be appreciated.


#importing modules

import arcpy.mapping as mapping
import arcpy

#obtaining map and layer properties

mxdPath = "C:\\Users\\jc\\Desktop\\Daily Work\\MXD\\.......\\.......mxd"

pointLayer = mapping.Layer("C:\\Users\\jc\\Desktop\\Daily Work\\layers\\Tracking_ND.lyr")

selectLayer = mapping.Layer("C:\\GIS_DATA_Static\\geodb\\PATrackingWebMc.gdb\\PLSS\\ND_PLSS_Township")

mxd = mapping.MapDocument(mxdPath)

mainDataFrame = mapping.ListDataFrames(mxd, "Main")[0]

def select_current_township(name, county):
    name.replace("\'", "\"")
    query = '"NAME" = \'' + name + '\' AND "COUNTY" = \'' + county + '\''
    print "selecting and creating cross layer  for" + name
    remove_selected_township()
    arcpy.MakeFeatureLayer_management(selectLayer, "selected", query)

def remove_selected_township():
    layers = mapping.ListLayers(mainDataFrame)
    for df in mapping.ListDataFrames(mxd):
        for lyr in mapping.ListLayers(mxd, "", df):
            if "selected" in lyr.name:
                print "deleting selected index layer"
                mapping.RemoveLayer(df, lyr)

for pageNumber in range(1, mxd.dataDrivenPages.pageCount + 1):
    mxd.dataDrivenPages.currentPageID = pageNumber
    pageName = mxd.dataDrivenPages.pageRow
    select_current_township(pageName.getValue("NAME"), pageName.getValue("COUNTY"))

Outcomes