Loop through list for multivalue input

575
4
07-06-2011 06:32 AM
RobertEhrman
New Contributor III
I have a folder with hundreds of shapefiles each representing a diff. state, each file starts with the prefix for that specific state e.g., al001r.shp, al003r.shp, fl001.shp, fl003.shp...etc.  What I'm trying to do is Append the shapefiles for each state into one shapefile via python, in the end having a single shapefile for each state.  I'm thinking I need to create a list of each of the prefixes and enumerate through the list thus creating a list of inputs for a multivalue input for the append?  This is about as far as I've gotten, can't figure out how to select just the first iteration and push to a list for multi-input?

dir = r"C:\temp"
gp.workspace = dir
print(dir)
files = os.listdir(dir)
alist = ['al', 'ct', 'dc', 'de', 'fl']
for file in files:
    sfile = file[0:2]
    if sfile in alist:
        alist[alist.index(sfile)] 
        print(sfile)
Tags (2)
0 Kudos
4 Replies
JakeSkinner
Esri Esteemed Contributor
Below is an example on how to do this.  The code adds all the shapefiles first two characters to a list, then removes the duplicates.  It will then merge the related shapefiles together to one shapefile.

lstFCs = arcpy.ListFeatureClasses("*")

list1 = []

# Append first two characters of each shapefile to list
for fc in lstFCs:
    list1.append(fc[0:2])

# Remove duplicates from list
list1 = dict.fromkeys(list1)
list1 = list1.keys()

# Merge feature classes
for n in list1:
    m = str(n) + "*"
    lstFCs = arcpy.ListFeatureClasses(m)
    arcpy.Merge_management(lstFCs, n + "_merge")
0 Kudos
RobertEhrman
New Contributor III
Thanks for the suggestion, the code below ended up working....kind of.  There's over 800 files and the code works like a dream until it gets to the 417th file, then I get a C++ Runtime Error! for Program: pythonw.exe????

 Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
dir = r"C:\temp"
output = r"C:\temp\shp"
gp.workspace = dir

fcs = gp.ListFeatureClasses("*")

x = '"%s"' % ';'.join(fcs)
print x
gp.Append(x, output, "NO_TEST")
print gp.getmessages()
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Try removing the 417th file and then re-execute the script to see if it works.  The file may be corrupted.
0 Kudos
RobertEhrman
New Contributor III
I tried that, it's not the problem. I can watch the memory build up, once it gets to a certain threshhold it bombs out????
0 Kudos