Merging Shapefiles – gp.merge_management()

I have been pulling my hair out all day to get this to work.

I have a number of folders, each containing one shapefile (stratmap transportation files – with county-wide data. I would like to combine (merge) all these files into one state-wide (Texas) shapefile.

I didn’t like doing it this way (using a long string concatenation in my merge method), but I was unable to get the value table version of this to work, as shown on the ESRI website (here or here). Nor was I successful with Bill’s workaround to that problem. Is this really an ArcGIS bug, or was I doing something wrong ?

I found it wasn’t entirely clear from the documentation that you can use a string in your merge. Using a list sure would be easier.

# ————————————————-
# A program that merges county-wide shapefile data
# and merges it into one state-wide shapefile.
# ————————————————-

# Create the Geoprocessor object
import os, sys, arcgisscripting, string
gp = arcgisscripting.create(9.3)

# Setup variables
gp.workspace = r”C:\Shp”  # The source directory
outshp = r’c:\shp\texas.shp’ # The output
fcstring = ” ”

# List all workspaces (folders)
workspaces = gp.listworkspaces(” “, “Folder”)

#Iterate through folders, set active workspace
for workspace in workspaces:
gp.workspace = workspace  # I found this was necessary

#List all feature classes (shapefiles) in folders
fcs = gp.ListFeatureClasses()

#Iterate through shapefiles
for fc in fcs:
#Create all shapefiles addresses (including)
# workspace in “;”-separated string for merging


#Merge shapefiles


The result of running this script was a convenient state wide file. Unfortunately, the size ballooned from a few MB per county to a 100MB SHP for the state, and an almost 1GB DBF.



Filed under Uncategorized

3 responses to “Merging Shapefiles – gp.merge_management()

  1. Ana

    Nameerror: name ‘workspace’ is not defined in line 28 — fcstring = ….

  2. lars

    You should use string interpolation to improve readability of your code. So fcstring=fcstring+str(workspace)+”\\”+str(fc)+”;” becomes fcstring += “%s\\%s;” % (fcstring, workspace, fc)

    • Arne

      Very good point, Lars. I’ve currently taking some Python 3 classes and now using the “string”.format() function a lot. You’re absolutely, it makes the code easier to read, and to maintain as well.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s