Adding shapefile name to attribute table?

03-01-2017 08:02 AM
New Contributor


I have a dataset with about 300 different shapefiles. I want to Merge all the shapefiles into one, but I need to keep the shapefile name. I have added a field to each of these shapefiles, but can't figure out how to populate the table with the name of the shapefile. I tried to download the Arc Toolbox "AddFieldName", but it didn't work. I also tried some of the Python codes and they also didn't work.

Any suggestions?


0 Kudos
4 Replies
MVP Regular Contributor

This could be done in Python.  Try running this before you run the merge. 

import arcpy
import os

SHPfolder = r'...path to folder where .shps are kept...'

for x in os.listdir(SHPfolder):
    with arcpy.da.UpdateCursor(SHPfolder + '/' + x, ['shpName']) as cursor: #Change field name if necessary
        for row in cursor:
            row[0] = str(x)
    del cursor
Occasional Contributor III

These links may assist you ... I believe %name% is reserved for model use....

arcgis desktop - How do you add file name to an attribute field? - Geographic Information Systems St... 

Batch add field, calculate field as filename 

This model may help you as well (I have no personal experience with it)....

ArcGIS Tool: Inserts file name into attribute table - 

Occasional Contributor III

To extend Mitch's answer, if your data is in a geodatabase rather than a folder, try the code below.

import arcpy
file_name_field = 'FNAME'
input_gdb_or_folder = r'c:\my.gdb'

arcpy.env.workspace = input_gdb_or_folder

feature_classes = arcpy.ListFeatureClasses()

for fc in feature_classes:
    print(fc) # just so you know what the script is processing
    # add field to hold the file name if it does not exist
    existing_fields = [ for f in arcpy.ListFields(fc)]
    if file_name_field not in existing_fields:, file_name_field, 'TEXT', field_length=200)
    # write the file name into each row of the file name filed
    with arcpy.da.UpdateCursor(fc, [file_name_field]) as uc:
        for row in uc:
    del row, uc‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍


New Contributor II

For anyone coming across this question (4 years later), this functionality is now available in the ArcGIS Pro Merge tool:

The tool has an "Add source information to output" checkbox - if you check it, it'll add a field named MERGE_SRC to the output:

The values in the MERGE_SRC field will indicate the input dataset path or layer name that is the source of each record in the output.

When I used it, I added layers to the tool from my Map, and the values in the resulting MERGE_SRC field looked like "GroupName\LayerName" (as named in the Map's Contents list). I haven't tried it with data added to the tool directly from browsing - maybe it puts the full pathname if you do it that way.