Select to view content in your preferred language

Convert Field Type to AddField_management keyword

2264
2
01-28-2016 01:55 PM
Labels (1)
curtvprice
MVP Alum
0 2 2,264

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
Luke_Pinner
MVP Regular Contributor

You're missing SHORT and TEXT types:

dtypes = {'OID': 'LONG', 'SmallInteger': 'SHORT', 'Integer': 'LONG', 
          'Double': 'DOUBLE', 'Single': 'FLOAT', 'String': 'TEXT', 
          'Date': 'DATE'}
curtvprice
MVP Alum

Thanks Luke. I also made a small change that makes it produce more useful error messages.

About the Author
PhD candidate (Geology), South Dakota Mines; Hydrologist, U.S. Geological Survey.