Python arcpy.ListFields() Examples

The following are 30 code examples of arcpy.ListFields(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module arcpy , or try the search function .
Example #1
Source File: CreateNetworkConnectivityFile.py    From python-toolbox-for-rapid with Apache License 2.0 6 votes vote down vote up
def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        try:
            if parameters[0].altered:
                field_names = []
                fields = arcpy.ListFields(parameters[0].valueAsText)
                for field in fields:
                    field_names.append(field.baseName.upper())
                if not ("HYDROID" in field_names and "NEXTDOWNID" in field_names):
                    parameters[0].setErrorMessage("Input Drainage Line must contain HydroID and NextDownID.")
        except Exception as e:
            parameters[0].setErrorMessage(e.message)

        if parameters[2].altered:
            max_nbr = parameters[2].value
            if (max_nbr < 0 or max_nbr > 12):
                parameters[2].setErrorMessage("Input Maximum Number of Upstreams must be within [1, 12]")
        return 
Example #2
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testadd_fields_from_table(self):
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.add_fields_from_table(copy, tab, flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #3
Source File: arcapi_test.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def testjoin_using_dict(self):
        if arcpy.Exists(r'in_memory\copy'):
            arcpy.Delete_management(r'in_memory\copy')
        fc = os.path.join(self.testing_gdb, 'Illinois')
        copy = fc + '_copy'
        if arcpy.Exists(copy):
            arcpy.Delete_management(copy)
        arcpy.CopyFeatures_management(fc, copy)
        flds = ['POP1990', 'POP2000']
        tab = fc = os.path.join(self.testing_gdb, 'Illinois_county_info')
        ap.join_using_dict(copy, 'CNTY_FIPS', tab, 'CNTY_FIPS', flds)
        est = [f.name for f in arcpy.ListFields(copy)]
        try:
            arcpy.Delete_management(copy)
        except: pass
        for f in flds:
            self.assertTrue(f in est)
        pass 
Example #4
Source File: CreateSubsetFile.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        try:
            if parameters[0].altered:
                field_names = []
                fields = arcpy.ListFields(parameters[0].valueAsText)
                for field in fields:
                    field_names.append(field.baseName.upper())
                if not ("HYDROID" in field_names and "NEXTDOWNID" in field_names):
                    parameters[0].setErrorMessage("Input Drainage Line must contain HydroID and NextDownID.")
        except Exception as e:
            parameters[0].setErrorMessage(e.message)

        return 
Example #5
Source File: SSURGO_Slope_Range_Inventory.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def getSecondSlope(slpRange):

    if not slpRange == "Slope N\A":

        if len(str(slpRange)) == 7:
            #AddMsgAndPrint("\n Processing7: " + slpRange + " -- " + str(len(slpRange)),2)
            return int(slpRange[slpRange.find('-') + 2:slpRange.find('-') + 3])

        else:
            #AddMsgAndPrint("\n Processing7: " + slpRange + " -- " + str(len(slpRange)),2)
            return int(slpRange[slpRange.find('-') + 2:slpRange.find('-') + 4])

    else:
        return 1000

## ===============================================================================================================
##def getSlopeNumber(table,rangeNum):
##
##    firstNumList = []
##
##    slpRangeField = [f.name for f in arcpy.ListFields(table,"SlopeRange")][0]
##    sql_expression = (None, 'ORDER BY ' + slpRangeField + ' ASC')
##
##    with arcpy.da.SearchCursor(table, (slp), sql_clause=sql_expression) as cursor:
##        for row in cursor:
##            slpRange = str(row[0])
##
##            if not slpRange == "None":
##
##                if len(str(slpRange)) == 7:
##                    firstNumber = int(slpRange[slpRange.find('-') + 2:slpRange.find('-') + 3])
##                    firstNumList.append(firstNumber,slpRange)
##
##                else:
##                    firstNumber = int(slpRange[slpRange.find('-') + 2:slpRange.find('-') + 4])
##                    firstNumList.append(firstNumber,slpRange)

## ====================================== Main Body ================================== 
Example #6
Source File: SSURGO_gSSURGO_byState.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def GetFieldList(tbi_1):
    # Create field list for MakeQueryTable

    try:
        fldList = ""

        pFld = arcpy.ParseTableName(os.path.basename(tbi_1)).split(",")
        db = pFld[0].strip()
        dbo = pFld[1].strip()
        tbl = pFld[2].strip()
        fldList = ""  # intialize fields string for MakeQuery Table
        # Create list of fields for export
        #PrintMsg("\nGetting fields for " + theTbl, 0)
        flds = arcpy.ListFields(tbi_1) # 9.3

        for fld in flds:              # 9.3
            fldp = fld.name
            fldq = db + "." + dbo + "."  + tbl + "." + fldp

            if fld.type != "OID":
                #PrintMsg("\nGetting name for field " + fldp, 0)

                if fldList != "":
                    fldList = fldList + ";" + fldq + " " + fldp

                else:
                    fldList = fldq + " " + fldp

        #PrintMsg(" \nOutput Fields: " + fldList, 0)
        return fldList

    except:
        errorMsg()
        return ""

## =================================================================================== 
Example #7
Source File: _data_objects.py    From registrant with MIT License 5 votes vote down vote up
def get_fields(self):
        """Get geodatabase table fields properties as ordered dicts."""
        fields = []
        for field_order, field in enumerate(arcpy.ListFields(self.path), 1):
            od = OrderedDict()
            od['UI order'] = field_order
            for k, v in GDB_TABLE_FIELD_PROPS.items():
                od[v] = getattr(field, k, '')
            fields.append(od)
        return fields

    # ---------------------------------------------------------------------- 
Example #8
Source File: arc_restapi.py    From restapi with GNU General Public License v2.0 5 votes vote down vote up
def append_feature_set(out_fc, feature_set, cursor):
    """Appends features from a feature set to existing feature class manually with an insert cursor.

    Args:
        out_fc: Output feature class path.
        feature_set: Input feature set.
        cursor: Insert cursor.
    """

    fc_fields = arcpy.ListFields(out_fc)
    cur_fields = [f.name for f in fc_fields if f.type not in ('OID', 'Geometry') and not f.name.lower().startswith('shape')]
    # insert cursor to write rows manually
    with arcpy.da.InsertCursor(out_fc, cur_fields + ['SHAPE@']) as irows:
        for i, row in enumerate(cursor(feature_set, cur_fields + ['SHAPE@'])):
            irows.insertRow(row) 
Example #9
Source File: parseVST.py    From CTM with Apache License 2.0 5 votes vote down vote up
def check_field(fc_class, field):
    print("Checking for " + field + " on " + fc_class)
    field_names = [f.name for f in arcpy.ListFields(fc_class)]
    if field not in field_names:
        arcpy.AddMessage("Adding Field to " + str(fc_class))
        arcpy.AddField_management(fc_class, field, "Long") 
Example #10
Source File: WMX_Generalization.py    From CTM with Apache License 2.0 5 votes vote down vote up
def setEdgeHierarchy(fcs, aoi, hier_field):
    """ sets the hierarchy of all features touching the aoi to 0"""
    arcpy.AddMessage("Setting hierarcy for edge features")
    for fc in fcs:
        fields = [f.name for f in arcpy.ListFields(fc)]
        if hier_field in fields:
            lyr = arcpy.MakeFeatureLayer_management(fc, "layera")
            arcpy.SelectLayerByLocation_management(lyr, "INTERSECT", aoi)
            arcpy.CalculateField_management(lyr, hier_field, "0")
            arcpy.Delete_management(lyr) 
Example #11
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def add_fields_from_table(in_tab, template, add_fields=[]):
    """Add fields (schema only) from one table to another

    Required:
    in_tab -- input table
    template -- template table containing fields to add to in_tab
    add_fields -- fields from template table to add to input table (list)

    Example:
    >>> add_fields_from_table(parcels, permits, ['Permit_Num', 'Permit_Date'])
    """

    # fix args if args from script tool
    if isinstance(add_fields, str):
        add_fields = add_fields.split(';')

    # grab field types
    f_dict = dict((f.name, [get_field_type(f.type), f.length, f.aliasName]) for f in arcpy.ListFields(template))

    # Add fields
    for field in add_fields:
        if field in f_dict:
            f_ob = f_dict[field]
            arcpy.AddField_management(in_tab, field, f_ob[0], field_length=f_ob[1], field_alias=f_ob[2])
            msg('Added field: {0}'.format(field))
    return 
Example #12
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def match_field(table_or_list, pat, multi=False):
    """Return a list of field objects where name matches the specified pattern.

    Required:
    table_or_list -- input table or feature class or list of fields
    pat -- pattern to match to field

    Optional:
    multi: if True, will return a list of all matches,
           otherwise returns the first match

    Example:
    >>> match_field(r'C:\Temp\Counties.shp', 'county_*', True)
    ['COUNTY_CODE', 'COUNTY_FIPS']
    """

    import fnmatch

    if isinstance(table_or_list, list):
        fields = table_or_list
    else:
        fields = [f.name for f in arcpy.ListFields(table_or_list)]
    all_mats = []
    for f in fields:
        if fnmatch.fnmatch(f, pat):
            if not multi:
                return f
            else:
                all_mats.append(f)
    return all_mats 
Example #13
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_field_type(in_field, fc=''):
    """Converts esri field type returned from list fields or describe fields
    to format for adding fields to tables.

    Required:
    in_field -- field name to find field type. If no feature class
        is specified, the in_field paramter should be a describe of
        a field.type

    Optional:
    fc -- feature class or table.  If no feature class is specified,
        the in_field paramter should be a describe of a field.type

    Example
    >>> # field type of 'String' needs to be 'TEXT' to be added to table
    >>> # This is a text type field
    >>> # now get esri field type
    >>> print getFieldType(table, 'PARCEL_ID') #esri field.type return is 'String', we want 'TEXT'
    TEXT
    """
    if fc:
        field = [f.type for f in arcpy.ListFields(fc) if f.name == in_field][0]
    else:
        field = in_field
    if field in lut_field_types:
        return lut_field_types[field]
    else:
        return None 
Example #14
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def rename_col(tbl, col, newcol, alias = ''):
    """Rename column in table tbl and return the new name of the column.

    This function first adds column newcol, re-calculates values of col into it,
    and deletes column col.
    Uses arcpy.ValidateFieldName to adjust newcol if not valid.
    Raises ArcapiError if col is not found or if newcol already exists.

    Required:
    tbl -- table with the column to rename
    col -- name of the column to rename
    newcol -- new name of the column

    Optional:
    alias -- field alias for newcol, default is '' to use newcol for alias too
    """
    if col != newcol:
        d = arcpy.Describe(tbl)
        dcp = d.catalogPath
        flds = arcpy.ListFields(tbl)
        fnames = [f.name.lower() for f in flds]
        newcol = arcpy.ValidateFieldName(newcol, tbl) #os.path.dirname(dcp))
        if col.lower() not in fnames:
            raise ArcapiError("Field %s not found in %s." % (col, dcp))
        if newcol.lower() in fnames:
            raise ArcapiError("Field %s already exists in %s" % (newcol, dcp))
        oldF = [f for f in flds if f.name.lower() == col.lower()][0]
        if alias == "": alias = newcol
        arcpy.AddField_management(tbl, newcol, oldF.type, oldF.precision, oldF.scale, oldF.length, alias, oldF.isNullable, oldF.required, oldF.domain)
        arcpy.CalculateField_management(tbl, newcol, "!" + col + "!", "PYTHON_9.3")
        arcpy.DeleteField_management(tbl, col)
    return newcol 
Example #15
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def types(x, filterer = None):
    """Return list of column types of a table.

    Required:
    x -- input table or table view

    Optional:
    filterer -- function, only fields where filterer returns True are listed

    Example:
    >>> types('c:\\foo\\bar.shp', lambda f: f.name.startswith('eggs'))
    """
    flds = arcpy.ListFields(x)
    if filterer is None: filterer = lambda a: True
    return [f.type for f in flds if filterer(f)] 
Example #16
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 5 votes vote down vote up
def names(x, filterer = None):
    """Return list of column names of a table.

    Required:
    x -- input table or table view

    Optional:
    filterer -- function, only fields where filterer returns True are listed

    Example:
    >>> names('c:\\foo\\bar.shp', lambda f: f.name.startswith('eggs'))
    """
    flds = arcpy.ListFields(x)
    if filterer is None: filterer = lambda a: True
    return [f.name for f in flds if filterer(f)] 
Example #17
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def fieldsToFieldArray(featureclass):
    """fieldsToFieldArray(featureclass)

       Converts fields to a list

         featureclass(String):
       The specified feature class or table whose fields will be returned.

    """
    fieldList = None
    try:
        fieldList = arcpy.ListFields(featureclass)
        returnFields = []
        for field in fieldList:
            returnFields.append(field.name)

        return returnFields
    except:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "fieldsToFieldArray",
            "line": line,
            "filename": filename,
            "synerror": synerror,
        }
        )
    finally:
        fieldList = None

        del fieldList

        gc.collect()


# ---------------------------------------------------------------------- 
Example #18
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 5 votes vote down vote up
def validate_schema_map(report_schema, reclass_map, report_date_field, report_ID_field):
    try:
        valid = True
        fieldList = arcpy.ListFields(report_schema)

        layer_fields = []
        for field in fieldList:
            layer_fields.append(field.name)

        for fld in reclass_map:
            if not fld['FieldName'] in layer_fields:
                print "%s does not exist in %s" % (fld['FieldName'], report_schema)
                valid = False
        if report_date_field == '':
            print "Warning: Report Date not set in %s" % (report_schema)
        elif not report_date_field in layer_fields:
            print "%s (Report Date Field) does not exist in %s" % (report_date_field, report_schema)
            valid = False
        if not report_ID_field in layer_fields:
            print "%s (ID Field) does not exist in %s" % (report_ID_field, report_schema)
            valid = False

        if valid == False:
            raise ReportToolsError({
                "function": "validate_schema_map",
                "line": 1454,
                "filename": 'reporttools',
                "synerror": "%s does not contain all the fields contained in the config" % report_schema
            })
    except arcpy.ExecuteError:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "validate_schema_map",
            "line": line,
            "filename": filename,
            "synerror": synerror,
            "arcpyError": arcpy.GetMessages(2),
        })
    except ReportToolsError, e:
        raise e 
Example #19
Source File: DataServicePillager.py    From DataPillager with MIT License 5 votes vote down vote up
def combine_data(fc_list, output_fc):
    """ :param fc_list: array of featureclass paths as strings
        :param output_fc: path to output dataset
        Combine the downloaded datafiles into one
        fastest approach is to use cursor
    """
    if len(fc_list) == 1:
        arcpy.Copy_management(fc_list[0], output_fc)
        output_msg("Created {0}".format(output_fc))
    else:
        for fc in fc_list:
            if fc_list.index(fc) == 0:
                # append to first dataset. much faster
                output_msg("Prepping yer first dataset {0}".format(fc))
                if arcpy.Exists(output_fc):
                    output_msg("Avast! {0} exists, deleting...".format(output_fc), severity=1)
                    arcpy.Delete_management(output_fc)
                
                arcpy.Copy_management(fc, output_fc)  # create dataset to append to
                output_msg("Created {0}".format(output_fc))

                fieldlist = []
                #fieldlist = ["SHAPE@"]
                fields = arcpy.ListFields(output_fc)
                for field in fields:
                    if field.name.lower() == u'shape':
                        fieldlist.insert(0, "SHAPE@") # add shape token to start
                    else:
                        fieldlist.append(field.name)
                #fields = [field.name for field in arcpy.ListFields(output_fc) if field.name.lower() not in [u'shape']]
                #fieldlist.extend(fields)
                ##arcpy.CopyFeatures_management(output_fc, fc) # duplicate first one so delete later doesn't fail
                insert_rows = arcpy.da.InsertCursor(output_fc, fieldlist)
            else:
                search_rows = arcpy.da.SearchCursor(fc, fieldlist) # append to first dataset
                for row in search_rows:
                    insert_rows.insertRow(row)
                del row, search_rows
                output_msg("Appended {0}...".format(fc))
        del insert_rows 
Example #20
Source File: spatial.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def getDateFields(fc):
    """
       Returns a list of fields that are of type DATE
       Input:
          fc - feature class or table path
       Output:
          List of date field names as strings
    """
    if arcpyFound == False:
        raise Exception("ArcPy is required to use this function")
    return [field.name for field in arcpy.ListFields(fc, field_type="Date")]
#---------------------------------------------------------------------- 
Example #21
Source File: general.py    From ArcREST with Apache License 2.0 5 votes vote down vote up
def fc_to_features(dataset):
        """
           converts a dataset to a list of feature objects
           Input:
              dataset - path to table or feature class
           Output:
              list of feature objects
        """
        if arcpyFound:
            desc = arcpy.Describe(dataset)
            fields = [field.name for field in arcpy.ListFields(dataset) if field.type not in ['Geometry']]
            date_fields = [field.name for field in arcpy.ListFields(dataset) if field.type =='Date']
            non_geom_fields = copy.deepcopy(fields)
            features = []
            if hasattr(desc, "shapeFieldName"):
                fields.append("SHAPE@JSON")
            del desc
            with arcpy.da.SearchCursor(dataset, fields) as rows:
                for row in rows:
                    row = list(row)
                    for df in date_fields:
                        if row[fields.index(df)] != None:
                            row[fields.index(df)] = int((_date_handler(row[fields.index(df)])))
                    template = {
                        "attributes" : dict(zip(non_geom_fields, row))
                    }
                    if "SHAPE@JSON" in fields:
                        template['geometry'] = \
                            json.loads(row[fields.index("SHAPE@JSON")])

                    features.append(
                        Feature(json_string=_unicode_convert(template))
                    )
                    del row
            return features
        return None
    #---------------------------------------------------------------------- 
Example #22
Source File: CreateMuskingumParameterFiles.py    From python-toolbox-for-rapid with Apache License 2.0 5 votes vote down vote up
def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        try:
            if parameters[0].altered:
                field_names = []
                fields = arcpy.ListFields(parameters[0].valueAsText)
                for field in fields:
                    field_names.append(field.baseName.upper())
                if not ("MUSK_KFAC" in field_names and "MUSK_K" in field_names and "MUSK_X" in field_names):
                    parameters[0].setErrorMessage("Input Drainage Line must contain Musk_kfac, Musk_k and Musk_x.")
        except Exception as e:
            parameters[0].setErrorMessage(e.message)

        return 
Example #23
Source File: gptools.py    From utilities-solution-data-automation with Apache License 2.0 4 votes vote down vote up
def assignFieldsByIntersect(sourceFC, assignFC, fieldsToAssign, outputFC,report_areas_overlap):
    tempWorkspace = arcpy.env.scratchGDB

    assignFields = arcpy.ListFields(dataset=assignFC)
    assignFieldsNames = [f.name for f in assignFields]

    sourceFields = arcpy.ListFields(dataset=sourceFC)
    sourceFieldNames = [f.name for f in sourceFields]
    newFields = []

    fms = arcpy.FieldMappings()
    for fieldToAssign in fieldsToAssign:
        if fieldToAssign not in assignFieldsNames:
            raise ValueError("{0} does not exist in {1}".format(fieldToAssign,assignFC))
        outputField = fieldToAssign
        if fieldToAssign in sourceFieldNames + newFields:
            outputField = Common.uniqueFieldName(fieldToAssign, sourceFieldNames + newFields)

        newFields.append(outputField)

        fm = arcpy.FieldMap()
        fm.addInputField(assignFC, fieldToAssign)
        type_name = fm.outputField
        type_name.name = outputField
        fm.outputField = type_name
        fms.addFieldMap(fm)



    fieldmappings = arcpy.FieldMappings()
    #fieldmappings.addTable(assignFC)
    #fieldmappings.removeAll()
    fieldmappings.addTable(sourceFC)
    for fm in fms.fieldMappings:
        fieldmappings.addFieldMap(fm)

    if report_areas_overlap:
        join_operation = "JOIN_ONE_TO_MANY"
    else:
        join_operation = "JOIN_ONE_TO_ONE"
    outputLayer = arcpy.SpatialJoin_analysis(target_features=sourceFC,
                                             join_features=assignFC,
                                             out_feature_class=outputFC,
                                             join_operation=join_operation,
                               join_type="KEEP_COMMON",
                              field_mapping=fieldmappings,
                              match_option="HAVE_THEIR_CENTER_IN",
                              search_radius=None,
                              distance_field_name=None)[0]


    return outputLayer 
Example #24
Source File: reporttools.py    From utilities-solution-data-automation with Apache License 2.0 4 votes vote down vote up
def FieldExist(featureclass, fieldNames):
    """FieldExist(dataset, [fieldNames])

       Determines if the array of fields exist in the dataset

         dataset(String):
       The specified feature class or table whose indexes will be returned.

         fieldNames{Array}:
       The the array of field name to verify existance."""
    fieldList = None
    fndCnt = None

    try:
        fieldList = arcpy.ListFields(featureclass)
        fndCnt = 0
        for field in fieldList:
            if field.name in fieldNames:
                fndCnt = fndCnt + 1

            if fndCnt > 0:
                return True
            del field
        if fndCnt != len(fieldNames):
            return False

    except:
        line, filename, synerror = trace()
        raise ReportToolsError({
            "function": "FieldExist",
            "line": line,
            "filename": filename,
            "synerror": synerror,
        }
        )
    finally:
        fieldList = None
        fndCnt = None

        del fieldList
        del fndCnt

        gc.collect()


# ---------------------------------------------------------------------- 
Example #25
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 4 votes vote down vote up
def create_field_name(fc, new_field):
    """Return a valid field name that does not exist in fc and
    that is based on new_field.

    Required:
    fc -- feature class, feature layer, table, or table view
    new_field -- new field name, will be altered if field already exists

    Example:
    >>> fc = 'c:\\testing.gdb\\ne_110m_admin_0_countries'
    >>> create_field_name(fc, 'NEWCOL') # NEWCOL
    >>> create_field_name(fc, 'Shape') # Shape_1
    """

    # if fc is a table view or a feature layer, some fields may be hidden;
    # grab the data source to make sure all columns are examined
    fc = arcpy.Describe(fc).catalogPath
    new_field = arcpy.ValidateFieldName(new_field, os.path.dirname(fc))

    # maximum length of the new field name
    maxlen = 64
    dtype = arcpy.Describe(fc).dataType
    if dtype.lower() in ('dbasetable', 'shapefile'):
        maxlen = 10

    # field list
    fields = [f.name.lower() for f in arcpy.ListFields(fc)]

    # see if field already exists
    if new_field.lower() in fields:
        count = 1
        while new_field.lower() in fields:

            if count > 1000:
                raise ArcapiError('Maximum number of iterations reached in uniqueFieldName.')

            if len(new_field) > maxlen:
                ind = maxlen - (1 + len(str(count)))
                new_field = '{0}_{1}'.format(new_field[:ind], count)
                count += 1
            else:
                new_field = '{0}_{1}'.format(new_field, count)
                count += 1

    return new_field 
Example #26
Source File: arc_restapi.py    From restapi with GNU General Public License v2.0 4 votes vote down vote up
def add_domains_from_feature_set(out_fc, fs):
    """Adds domains from a feature set to a feature class.

    Args:
        out_fc: The output feature class path.
        fs: Input feature set.
    """

    # find workspace type and path
    ws, wsType = find_ws_type(out_fc)
    isShp = wsType == 'FileSystem'
    if not isShp:
            gdb_domains = arcpy.Describe(ws).domains
            dom_map = {}
            for field in fs.fields:
                if field.get(DOMAIN):
                    field_name = field.name.split('.')[-1]
                    dom_map[field_name] = field.domain[NAME]
                    if field.domain[NAME] not in gdb_domains:
                        if CODED_VALUES in field.domain:
                            dType = CODED
                        else:
                            dType = RANGE_UPPER
                        arcpy.management.CreateDomain(ws, field.domain[NAME],
                                                          field.domain[NAME],
                                                          FTYPES[field.type],
                                                          dType)

                        try:

                            if dType == CODED:
                                for cv in field.domain[CODED_VALUES]:
                                    arcpy.management.AddCodedValueToDomain(ws, field.domain[NAME], cv[CODE], cv[NAME])

                            elif dType == RANGE_UPPER:
                                _min, _max = field.domain[RANGE]
                                arcpy.management.SetValueForRangeDomain(ws, field.domain[NAME], _min, _max)

                        except Exception as e:
                            warnings.warn(e)

                        gdb_domains.append(field.domain[NAME])
                        print('Added domain "{}" to database: "{}"'.format(field.domain[NAME], ws))

            # add domains
            field_list = [f.name.split('.')[-1] for f in arcpy.ListFields(out_fc)]
            for fld, dom_name in six.iteritems(dom_map):
                if fld in field_list:
                    arcpy.management.AssignDomainToField(out_fc, fld, dom_name)
                    print('Assigned domain "{}" to field "{}"'.format(dom_name, fld)) 
Example #27
Source File: FlowlineToPoint.py    From python-toolbox-for-rapid with Apache License 2.0 4 votes vote down vote up
def execute(self, parameters, messages):
        """The source code of the tool."""
        arcpy.env.overwriteOutput = True

        # Script arguments
        Input_Features = parameters[0].valueAsText
        Output_Table = parameters[1].valueAsText
        Intermediate_Feature_Points = os.path.join("in_memory","flowline_centroid_points")

        # Process: Feature To Point
        arcpy.AddMessage("Converting flowlines to points ...")
        arcpy.FeatureToPoint_management(Input_Features, Intermediate_Feature_Points, "CENTROID")

        # Process: Add XY Coordinates
        arcpy.AddMessage("Adding XY coordinates to points ...")
        arcpy.AddXY_management(Intermediate_Feature_Points)

        # write only desired fields to csv
        arcpy.AddMessage("Writing output to csv ...")
        original_field_names = [f.name for f in arcpy.ListFields(Intermediate_Feature_Points)]
        #COMID,Lat,Lon,Elev_m
        actual_field_names = ["", "", "", ""]
        for original_field_name in original_field_names:
            original_field_name_lower = original_field_name.lower()
            if original_field_name_lower == 'comid':
                actual_field_names[0] = original_field_name
            elif original_field_name_lower == 'hydroid':
                if not actual_field_names[0]:
                    actual_field_names[0] = original_field_name
            elif original_field_name_lower == 'point_y':
                actual_field_names[1] = original_field_name
            elif original_field_name_lower == 'point_x':
                actual_field_names[2] = original_field_name
            elif original_field_name_lower == 'point_z':
                if not actual_field_names[3]:
                    actual_field_names[3] = original_field_name

        #check to make sure all fields exist
        for field_name in actual_field_names:
            if field_name == "":
                messages.addErrorMessage("Field name %s not found." % field_name)
                raise arcpy.ExecuteError

        #print valid field names to table
        with open(Output_Table, 'wb') as outfile:
            writer = csv.writer(outfile)
            writer.writerow(['COMID','Lat','Lon','Elev_m'])
            with arcpy.da.SearchCursor(Intermediate_Feature_Points, actual_field_names) as cursor:
                for row in cursor:
                    #make sure all values are valid
                    np_row = array(row)
                    np_row[isnan(np_row)] = 0
                    writer.writerow([int(row[0]), row[1], row[2], row[3]])

        arcpy.AddMessage("NaN value(s) replaced with zero. Please check output for accuracy.")

        return 
Example #28
Source File: Validate_Mapunit_Slope_Range.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def getZoneField(muLayerPath, analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # the field exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:

        theDesc = arcpy.Describe(muLayerPath)
        theFields = theDesc.fields
        theField = theFields[0]
        idField = theDesc.OIDFieldName

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayerPath,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayerPath, "MLRA_Temp")) > 0:
                    arcpy.AddField_management(muLayer,"MLRA_Temp","TEXT", "", "", 15)

                arcpy.CalculateField_management(muLayer,"MLRA_Temp", "\"MLRA Mapunit\"", "PYTHON_9.3", "")
                return "MLRA_Temp"

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayerPath, "MLRA_Temp")) > 0:
                arcpy.AddField_management(muLayer,"MLRA_Temp","TEXT", "", "", 15)

            arcpy.CalculateField_management(muLayer,"MLRA_Temp", "\"MLRA Mapunit\"", "PYTHON_9.3", "")
            return "MLRA_Temp"

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return ""

## =============================================================================================================== 
Example #29
Source File: Mapunit_Geodata_Breakdown_Description.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def getZoneField(analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # it exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:
        mlraTempFld = "MLRA_Temp"

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayerPath,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayerPath,mlraTempFld)) > 0:
                    arcpy.AddField_management(muLayerPath,mlraTempFld,"TEXT", "", "", 15)

                # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
                with arcpy.da.UpdateCursor(muLayerPath,mlraTempFld) as cursor:
                    for row in cursor:
                        row[0] = "MLRA_Mapunit"
                        cursor.updateRow(row)

                return mlraTempFld

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayerPath,mlraTempFld)) > 0:
                arcpy.AddField_management(muLayerPath,mlraTempFld,"TEXT", "", "", 15)
                arcpy.RefreshCatalog(outputFolder)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayerPath,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return mlraTempFld

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return False

# =================================================================================== 
Example #30
Source File: Area_Geodata_Breakdown_Description.py    From geo-pit with GNU General Public License v2.0 4 votes vote down vote up
def getZoneField(analysisType):
    # This function will return a field name based on the analysis type that
    # was chosen by the user.  If analysis type is MUKEY, then MUKEY is returned if
    # it exists, otherwise a newly created field "MLRA_Temp" will be returned.
    # "MLRA_Temp" will be returned for MLRA analysis type
    # OID field will be returned for each polygon

    try:
        mlraTempFld = "MLRA_Temp"

        if analysisType.find('Mapunit (MUKEY)') > -1:

            if len(arcpy.ListFields(muLayer,"MUKEY")) > 0:
                return "MUKEY"
            else:
                AddMsgAndPrint("\nAnalysis Cannot be done by Mapunit since MUKEY is missing.",1)
                AddMsgAndPrint("Proceeding with analysis using MLRA ",1)

                if not len(arcpy.ListFields(muLayer,mlraTempFld)) > 0:
                    arcpy.AddField_management(muLayer,mlraTempFld,"TEXT", "", "", 15)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayer,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return "MLRA_Temp"

        elif analysisType.find('MLRA Mapunit') > -1:
            if not len(arcpy.ListFields(muLayer,mlraTempFld)) > 0:
                arcpy.AddField_management(muLayer,mlraTempFld,"TEXT", "", "", 15)
                arcpy.RefreshCatalog(outputFolder)

            # Calculate the new field using an UpdateCursor b/c Calc tool threw an 000728 error
            with arcpy.da.UpdateCursor(muLayer,mlraTempFld) as cursor:
                for row in cursor:
                    row[0] = "MLRA_Mapunit"
                    cursor.updateRow(row)

            return "MLRA_Temp"

        # Analysis Type = Polygon
        else:
            AddMsgAndPrint("\nWARNING Reporting by polygon might be very verbose")
            return idField

    except:
        errorMsg()
        return False

# ===================================================================================