zackb11

ArcPy - add multiple shapefiles with for loop

Discussion created by zackb11 on Feb 10, 2012
Latest reply on May 16, 2012 by zesandler
I have a folder that contains a few dozen shapefiles.  I want to create a script that adds all of these files to the current map document.  The script asks the user for a map ID (which decides what folder to load the shapefiles from).

I have the following thus far:

import arcpy, os, glob

# Set Workspace
base_Folder = r"N:\BASE_DATA\CANVEC\1_to_50k"
arcpy.env.Workspace = base_Folder
arcpy.env.OverwriteOutput = True

# User input for NTS mapsheet name.  This variable is also used to search for the correct mapsheet.
map_No = arcpy.GetParameterAsText(0)

# Canvec data is stored in folders, broken down by 1:50000 mapsheet number (eg: 031, 001, 045, etc).
# This variable extracts the folder name to be used when finding the correct folder
folder_Name = map_No[0:3]
# print folder_Name

#Established the correct folder to look in when loading the specified layers.
search_Folder = base_Folder + "\\" + folder_Name + "\\" + map_No
print search_Folder

##mxd = arcpy.mapping.MapDocument("CURRENT")
##dataFrame = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
shp_List = arcpy.ListFiles("*.shp")
for layer in shp_List:
    mxd = arcpy.mapping.MapDocument("CURRENT")
    dataFrame = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]
    layer_Path = search_Folder + "\\" + layer
    addLayer = arcpy.mapping.Layer(layer_Path)
    arcpy.mapping.AddLayer(dataFrame, addLayer, "BOTTOM")
    arcpy.RefreshTOC()
    arcpy.RefreshActiveView()
    del addLayer, layer_Path, mxd


I load the script into ArcToolbox.  The script executes without error, but no layers are added to my map document.

I understand there are some redundant or unnecessary lines of code in here, but I think the problem is coming from the for loop.

Any ideas?

Thanks

Outcomes