[GIS] Merge Shapefiles and Add File Name to Attribute Table

arcgis-10.3arcpymergetable

I am trying to merge lots of point shapefiles together to form 1 large shapefile. What i want to be able to do is get the name of each of the point files to appear in the attribute table either during the merge or carrying out a post processing task. How can i do this in ArcMap 10.3? I also have no experience with python code etc.

Best Answer

Without coding, it could be time-consuming. Either way, the steps would be to add a field to each shapefile and populate each feature with the shapefile's name. Here's a sample script, to give you an idea, if you'd like to try coding.

import arcpy
import os

# Set the ArcPy workspace to the directory that contains your input shapefiles
arcpy.env.workspace = r'C:\data\WhereTheShapefilesAre'

# Get a list of shapefiles in the workspace
fcs_in = arcpy.ListFeatureClasses()
print 'fcs_in:', fcs_in

fn_source_field = 'SOURCE_SHP'

# Iterate over the shapefiles
for fc in fcs_in:
    print 'fc:', fc
    # Get the shapefile's name without the extension
    name = os.path.splitext(fc)[0]
    # Add the source field to the shapefile
    arcpy.AddField_management(fc, fn_source_field, 'TEXT')
    # Iterate over the rows, populating the source field with the shapefile's
    #   name
    with arcpy.da.UpdateCursor(fc, fn_source_field) as cur:
        for row in cur:
            row[0] = name
            cur.updateRow(row)

# The path/name of your output, merged shapefile
fc_output = r'C:\data\MyOutputDirectory\MyOutputShapefile.shp'
# Merge the shapefiles
arcpy.Merge_management(fcs_in, fc_output)

You shouldn't have to change much for your situation. Change C:\data\WhereTheShapefilesAre to the directory that contains your input shapefiles. Change C:\data\MyOutputDirectory\MyOutputShapefile.shp to wherever you'd like the merged shapefile to be.

After you make those changes, put it into a text file and give it a .py extension. Then, you can simply double click the file from Windows Explorer, and it should run.

Note that this script will alter your original files, by adding a field named 'SOURCE_SHP' and populating it with the shapefile's name.

==EDIT==

I added a couple print statements to the code to help you identify the issue.

Related Question