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.
This could be done in Python. Try running this before you run the merge.
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 = str(x)
These links may assist you ... I believe %name% is reserved for model use....
This model may help you as well (I have no personal experience with it)....
To extend Mitch's answer, if your data is in a geodatabase rather than a folder, try the code below.
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 = [f.name for f in arcpy.ListFields(fc)]
if file_name_field not in existing_fields:
arcpy.management.AddField(fc, 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