Merge all shapefiles in directory for 10.1

2949
2
09-06-2012 07:33 AM
ChrisHanes1
New Contributor
I am trying to move some scripts from 9.3 over to 10.1 and a portion of my script is hanging up on the merge tool.  Below is the code from 9.3 pertaining to the merge (tested and worked).  Obviously I set Input_Workspace at run time.  The goal is to merge all shapefiles in the directory.  All are same type (polygon):

print "\nSetting the current workspace to: " + Input_Workspace + "...\n"
gp.Workspace = Input_Workspace

# Delete Merge file if exists...
merged_file = Input_Workspace + '/' + "Exp_merged.shp"
if gp.Exists(merged_file):
    gp.Delete(merged_file)
    print "Merge file exists, deleted...\n"

# Start a blank list for appending
list = []

# For each file in the current directory
for file in os.listdir(Input_Workspace):
    # Get files that end with *.shp
    if (file.endswith("shp")):

        # Append all the files together into one big list
        filepath = list.append(file)

        # Hard-code the output merged shapefile name
        shapefile = "Exp_merged.shp"

        # Given a list of shapefiles, separate each by a ";"
        # and put quotes around the whole thing
        def Lst(filepath):
            return '"%s"' % ';'.join(list)

# Set the variable "mergedlist" to the newly formatted list of shapefiles
mergedlist = Lst(filepath)
print "Merging exports...\n"
gp.merge_management(mergedlist, shapefile)
print "Merged " + mergedlist + " to get " + shapefile + "...\n"


Can anybody help me convert this?  I have tried changing the semicolon to a comma (as it appears arcpy merge wants a different format for the input).  If you have a better way I am of course open to that.
Tags (2)
0 Kudos
2 Replies
MathewCoyle
Frequent Contributor
Seems unnecessarily verbose.

import arcpy as gp

gp.env.workspace = r"your_input_path"
feature_list = gp.ListFeatureClasses("*.shp", "Polygon")
out_fc = r"your_output_path"
gp.Merge_management(feature_list, out_fc)
0 Kudos
ChrisHanes1
New Contributor
I will give that a shot.  I think I had the merge right in my last attempt, but it gave me a field warning (couldn't populate it with a value).  I think that value is simply too long because the length is variable between shapefiles (the process that creates them unfortunately chops the length of text fields to the longest value in it. 

So, I think I am going to have to scrap the merge and just append them all to a feature class with the correct schema already.

I am hoping this works (list is the same value from my previous code, or feature_list in your code):

AppendTarget = thisGDB + '/' + "Exp_merged"
arcpy.Append_management (list, AppendTarget, "NO_TEST")
0 Kudos