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
3 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
Regular Contributor II

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‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍