I am trying to loop through a list of layers in a folder, add each layer to an mxd and export an image of the added layer. I have added arcpy.mapping.RemoveLayer to the script to remove the added layer before adding the next layer, but it's not working the way I thought it would and is adding all the layers to the mxd and exporting after each one is added without removing the layer. I'm not sure if it's not nested/indented correctly, or if I'm not saving the map document at the right point(s). So, to recap, the script is successfully adding each layer to the mxd and exporting an image after each layer is added, but is not removing the layer after exporting.
It should be Add Layer 1>Export Image 1>Remove Layer 1; Add Layer 2>Export Image 2>Remove Layer 2; Continue Through List.
Here is what I have:
mxdPath = mxd path on disk mxd = arcpy.mapping.MapDocument(mxdPath) df = arcpy.mapping.ListDataFrames(mxd) imageFolder = path to image folder on disk lyrFolder = path to folder of physical layer files on disk arcpy.env.workspace = lyrFolder rasterLayers = arcpy.ListFiles("*.lyr") for layer in rasterLayers: image = imageFolder+"/"+layer[:-8]+".jpg" layerPath = lyrFolder+"/"+layer addlyr = arcpy.mapping.Layer(layerPath) arcpy.mapping.AddLayer(df,addlyr,"TOP") mxd.save() arcpy.mapping.ExportToJPEG(mxd,image) arcpy.mapping.RemoveLayer(df,addlyr) mxd.save()
I've also tried, to no avail:
for layer in rasterLayers: ... arcpy.mapping.AddLayer(df,addlyr,"TOP") mxd.save() arcpy.mapping.ExportToJPEG(mxd,image) # Delete and recreate map document object after saving to reflect added layer in ListLayers del mxd mxd = arcpy.mapping.MapDocument(mxdPath) for lyr in arcpy.mapping.ListLayers(mxd,"D_*"): #All layers in lyrFolder start with "D_" arcpy.mapping.RemoveLayer(df,lyr) mxd.save()
I'm sure I've missed something simple, but I'm stumped at this point.