Skip to content

Instantly share code, notes, and snippets.

@hwidlund
Last active May 7, 2016 20:02
Show Gist options
  • Select an option

  • Save hwidlund/3af2fe1861f14ba334563e8e59d7a6ae to your computer and use it in GitHub Desktop.

Select an option

Save hwidlund/3af2fe1861f14ba334563e8e59d7a6ae to your computer and use it in GitHub Desktop.
Snippet to truncate feature class field to new length
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment