Failed on input OID…
Ever had an append or other operation fail because you are trying to squeeze a longer field into a shorter field?

While it’s neat that you can now change text field lengths in ArcCatalog, you can only increase them, not decrease them. When I was working on standardizing schemas with another agency, we went through a long process to create a new field, calculate the right number of characters into it, delete the old field, create a new field with the old name and the new length, calculate the values from the “holding” field, then delete the “holding” field.
Here is a snippet (which can also be modified to be a script tool) which takes the feature class, the name of the field to truncate, and a new length, and does this process for you. It doesn’t have messaging or error checking, so you’d have to add those in.
| import arcpy | |
| # get parameters | |
| fc = "c:/geodatabase.gdb/featureclass" ## feature class | |
| field = "field" ## name of field to truncate | |
| newLength = 100 ## new length: whatever is needed | |
| # create new name, length, expression to truncate existing data | |
| newField = field + "tmp" | |
| newLengthSlice = newLength - 1 | |
| # the expression slices up to the new field length | |
| # uses string formatting to insert field name and new length | |
| exp = "!{0}![0:{1}]".format(field, newLengthSlice) | |
| # get list of field names using list comprehension | |
| fieldNames = [f.name for f in arcpy.ListFields(fc)] | |
| # if the "new" field already exists, delete it | |
| if newField in fieldNames: | |
| arcpy.DeleteField_management(fc, newField) | |
| # add new field specifying target length | |
| arcpy.AddField_management(fc,newField,"TEXT","","",newLength) | |
| # calculate the new field using the expression which brings in only | |
| # the left-most characters up to the character limit you specified (the new length) | |
| arcpy.CalculateField_management(fc,newField,exp,"PYTHON_9.3") | |
| # delete the old, too-big field | |
| arcpy.DeleteField_management(fc,field) | |
| # add a new field, named the same as the old field, with the new length | |
| arcpy.AddField_management(fc,field,"TEXT","","",newLength) | |
| # create second expression to populate the new/old field | |
| exp2 = "!{0}!".format(newField) | |
| # calculate field using second expression | |
| arcpy.CalculateField_management(fc,field,exp2,"PYTHON_9.3") | |
| # delete the field you used to make the transfer | |
| arcpy.DeleteField_management(fc,newField) |
ArcGIS Desktop documentation: