[GIS] Looping through Layers, Add Layer to MXD, Export Image, Repeat, using ArcPy

arcgis-10.2arcpyloop

ArcGIS 10.2.2

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)[0]

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.

Best Answer

RefreshActiveView is necessary and mxd.save is not useful in your case. But rather than adding an removing the layer, here is a script that should help you update your layer.

ly = arcpy.mapping.ListLayers(mxd)[0] #note : the top layer should already be present in the mxd 
for layer in rasterLayers:
    # update with the new path
    arcpy.mapping.UpdateLayer(df, ly, layer, False)
    arcpy.mapping.ExportToJPEG(mxd,imageFolder+"/"+layer[:-8]+".jpg")