I have a mxd with 3 dataframe: 'layers', 'geography' and 'book'.
'layers' dataframe has 2 layers: 'gridIndexFeatures' and 'zone'.
'geography' and 'book' datasets are empty.
I want to add the 'gridIndexFeatures' layer to 'book' dataframe by means of a Python script, but I want to check if that layers was previously added so as to not add it again.
I wrote the following code:
def cargacapas(capa, alias, dataframe, mxd_path):
arcpy.MakeFeatureLayer_management(capa, alias)
DF = arcpy.mapping.ListDataFrames(mxd_path)[dataframe]
layer = arcpy.mapping.Layer(alias)
if not arcpy.Exists(layer):
arcpy.mapping.AddLayer(DF, layer, "AUTO_ARRANGE")
else:
print "it exists so I don't add it again"
mxd_path.save()
del mxd_path
mxd = arcpy.mapping.MapDocument(r"U:\Proyectos\book1.mxd")
grid_path = r"U:\Proyectos\EDAR.gdb\gridIndexFeatures"
inFeatures = r"U:\Proyectos\EDAR.gdb\zone"
cargacapas(inFeatures, "Zona_de_ocupacion", 2, mxd)
cargacapas(grid_path, "Grid", 2, mxd)
My problem is that the EXISTS function detect 'gridIndexFeatures' exists in the 'layers' dataframe and return a True. But I need to detect if it exists in the 'book' dataframe.
Any help with this issue?
I have changed the code like this:
def cargacapas(capa, alias, dataframe, mxd_path):
arcpy.MakeFeatureLayer_management(capa, alias)
DF = arcpy.mapping.ListDataFrames(mxd_path)[dataframe]
layer = arcpy.mapping.Layer(alias)
if layer not in [lyr.name for lyr in arcpy.mapping.ListLayers(mxd_path,"", DF)]:
arcpy.mapping.AddLayer(DF, layer, "AUTO_ARRANGE")
else:
print "it exists"
mxd_path.save()
del mxd_path
But it not seems to work propertly. Each time I run the code, it add the two layers, so it doesn't detect that those layers are already in the dataframe.
Best Answer
arcpy.Exists
checks for the existence of a layer in your current workspace (Esri), not in the current map dataframe. If you want to check if it exists in a dataframe (e.g. "book"), you could try something like...I've changed your reference to
dataframe
here as that's dependent on the order of your dataframes in the map doc. Feel free to remove the wildcards and change that back to your previous method, as long asbookDF
andlayersDF
refer to the appropriate positions of those dataframes.