Convert Field Type to AddField_management keyword

1415
2
01-28-2016 01:55 PM
Labels (1)
curtvprice
MVP Esteemed Contributor
0 2 1,415

This function maps the field types reported by Describe or Field to the keyword used by the Add Field tool.

def AddFieldType(tbl, field_name):
    """Determines keyword to create a field with the AddField tool of
    the same type as the specified field.


    Integer > "LONG", Float -> "SINGLE" etc


    example


    AddFieldType("test.dbf", "Shape_Leng")
    "DOUBLE"
    arcpy.AddField_management("test.dbf", "Shape_Len2",
                              AddFieldType("test.dbf", "Shape_Leng"))
    """
    dtypes = {'OID': 'LONG', 'SmallInteger': 'SHORT', 'Integer': 'LONG',
              'Double': 'DOUBLE', 'Single': 'FLOAT', 'String': 'TEXT',
              'Date': 'DATE'}
    fld_list = arcpy.Describe(tbl).Fields
    ftype = [f.type for f in fld_list
             if f.name.upper() == field_name.upper()]
    if not ftype:
        raise Exception("Field {} not found".format(field_name))
    ftype = ftype[0]
    try:
        return dtypes[ftype]
    except KeyError:
        msg = "{}: field type {} not supported".format(field_name, ftype)
        raise Exception(msg)
Tags (2)
2 Comments
About the Author
PhD candidate (Geology), South Dakota Mines; Hydrologist, U.S. Geological Survey.
Labels