Batch add field, calculate field as filename

01-02-2014 12:06 PM
New Contributor II
So here is my last and final question and unfortunately my largest hurdle.  I have a tonne of shapefiles (4249 to be exact).  I have never used a model builder or scripted anything.  I need to somehow batch add a field (named RTENO) and assign the shapefile name to that field.  The only other option I have is to batch calculate field with file name one at a time over 4000 times. If anyone knows of anything I could do to make this possible it would be a life saver.
6 Replies
New Contributor III

If I were you, I would use model buider and do the following:

1. Use iterator to read the feature classes that you would like to run. While excuting iterator, model builder will generate a system variable (it should originally show up as 'Name' in iterator), which stores the file name.

2. Use Add Field tool to add field.

3. Use Calculate field. This is when you need to use that system variable, use %Name% to get the feature class' name,

Hope this helps!
0 Kudos
Esri Esteemed Contributor
Hi Jason,

Here is a script you can run:

import arcpy
from arcpy import env
env.workspace = r"C:\DATA"

for shapefile in arcpy.ListFeatureClasses("*"):
    name = shapefile.split(".")[0]
    arcpy.AddField_management(shapefile, "RTENO", "TEXT")
    arcpy.CalculateField_management(shapefile, "RTENO", '"' + name + '"', "PYTHON")

You will just need to change the 'env.workspace' to the directory path of your shapefiles.  Don't forget to include the 'r' before the path.
Occasional Contributor II

Hi, i know it's an old conversation but you don't know why it doesn't work for me?

var AL016 = "MS_FT_AL016_T";
 var typObjektu = "TYP_OBJEKTU";
                var NF103 = "MS_FT_NF103_T";
                var NF109 = "MS_FT_NF109_T";
                var NF121 = "MS_FT_NF121_T";
                var NF127 = "MS_FT_NF127_T";
                var NF128 = "MS_FT_NF128_T";
                var FTJmeno = "MS_FT_JMENO_P_T";
List<string> names = new List<string>();
                foreach (var name in names)
                    FeatureLayer featureLayer = mv.Map.FindLayers(name).First() as FeatureLayer;
                    FeatureClass fc = featureLayer.GetTable() as FeatureClass;
                    await AddField(fc, typObjektu, "TEXT", "", "", 10);
                    object[] paraList = { fc, typObjektu, '"' + name + '"' }; //always comes NULL in the column
                    await StartATask("management.CalculateField", paraList);
0 Kudos
New Contributor II

Does this work for Ratsers too? 

I don't think, with a few changes, where the feature classes are mentioned, I denoted Rasters - but nothing works!!!

Also, the simple %name% - doesn't work!!

0 Kudos
New Contributor II
Thank you both.  This was a huge time saver. Really wish I was more comfortable with scripting tools. The time I could have saved.
0 Kudos
Esri Esteemed Contributor
0 Kudos