[GIS] How to calculate Field using part of filename in ModelBuilder

arcgis-desktopmodelbuilder

I am new to ModelBuilder and have not been able to figure how to use part of the FC name: For example the first FC in my GDB containing around 100 files is "A1005_GPS_Residence", and I need to calculate the new field SID = "A1005".

I have seen some posts with python and manually using the Field Calculator.

I tried using one expression, shown in the screenshot, but I am not sure if I can combine field calculations with inline substitution or the like !%Name%![1:4].

Screenshot of MB

Best Answer

I have attached a python script that should steer you in the right direction. You will find that custom naming in loops is much easier in python than model builder.

EDIT: Added additional code to address new information

# Import standard library modules
import arcpy, os, sys
from arcpy import env

# Allow for file overwrite
arcpy.env.overwriteOutput = True

# Set the workspace directory 
env.workspace = r"C:\temp.gdb" 

# Get the list of the featureclasses to process
fc_tables = arcpy.ListFeatureClasses()

# Loop through each file and perform the processing
for fc in fc_tables:
    print str("processing " + fc)

    # Define field name and expression
    field = "SID"
    expression = str(fc[:5]) #subsets first 5 characters of fc name

    # Create a new field with a new name
    arcpy.AddField_management(fc,field,"TEXT")

    # Calculate field here
    arcpy.CalculateField_management(fc, field, "expression", "PYTHON") 

enter image description here

Related Question