Select to view content in your preferred language

ArcPy - add multiple shapefiles with for loop

8980
10
02-10-2012 10:50 AM
ZackBartlett
Regular Contributor
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
Tags (2)
0 Kudos
10 Replies
ZachErbe
New Contributor
I ended up using the Command Prompt (cmd.exe) and the xcopy function to move the files around.

Below is an example of the code I used:

xcopy 43121\zone.* User\state\zone_43121.*


Leaving the .* for the source directory and the destination directory enabled xcopy to copy all four shapefiles (.shp, .dbf, .shx, .prj).
0 Kudos