[GIS] How to iterate through layers of an MXD

arcmaparcpyiteratorlayers

I know model builder will not iterate through the layers in an MXD, which is kind of fundamentally stupid if you ask me, but I still need to do exactly that. I am not a strong coder but i understand Python is how to handle this.

I have seen other questions addressing this, but they seem over-my-head in complexity (i have taken an 'intro to python' university course and did well in it, plus did all the ESRI tutorials, still doesn't help understand how this works). I am hoping someone here can post some simple cut-n-paste python I can use to accomplish this.

I need to iterate through the ToC and export each layer as a shapefile to a specific folder. The folder is always the same, but the ToC will change depending on the application, so I have different MXD's for each subset of layers that need to be exported, which is why i want to script/model this as then i can open any MXD and run a tool to get my outputs.

Best Answer

To answer your specific question "How to iterate through layers of an MXD?"

mxd = arcpy.mapping.MapDocument("CURRENT")  # Uses your currently open MXD
df = arcpy.mapping.ListDataFrames(mxd, '')[0] # Chooses the first dataframe
for lyr in arcpy.mapping.ListLayers(mxd, '', df): # Loop through layers
    # Any tools you want to run on each layer go here

Something like this should work - just gets a list of all layers in your current map and outputs them to a single folder as shapefiles.

import arcpy

mxd = arcpy.mapping.MapDocument("CURRENT")  # Uses your currently open MXD
df = arcpy.mapping.ListDataFrames(mxd, '')[0] # Chooses the first dataframe

destPath = r"N:/VisualStudio/Projects/GISSE/Output" # Set your destination folder path

for lyr in arcpy.mapping.ListLayers(mxd, '', df): # Loop through layers
    # Output layer to shapefile
    arcpy.FeatureClassToFeatureClass_conversion(lyr, destPath, "{}.shp".format(lyr), "", "", "")