Python arcpy.SelectLayerByAttribute_management() Examples

The following are 7 code examples of arcpy.SelectLayerByAttribute_management(). 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: CreateDischargeMap.py    From python-toolbox-for-rapid with Apache License 2.0 7 votes vote down vote up
def copyFlowlines(self, in_drainage_line, path_database, list_uniqueID):
        """Create copies of flowlines based on the layer query definitions"""
        # make a feature layer for query selection
        name_lyr = "flowlines"
        arcpy.MakeFeatureLayer_management(in_drainage_line, name_lyr)

        '''Create the query expression for line features with matching records in the flat table'''
        expression_base = self.name_ID + " IN ("
        count = len(list_uniqueID)
        counter = 1
        for each_ID in list_uniqueID:
            if counter == count:
                expression_base = expression_base + str(each_ID) + ")"
            else:
                expression_base = expression_base + str(each_ID) + ", "
            counter += 1


        for each_key in self.layer_minScale_maxScale_query.keys():
            out_copy = os.path.join(path_database, "Flowline_"+each_key)
            pars = self.layer_minScale_maxScale_query[each_key]
            query = pars[2]
            expression = expression_base
            if query is not None:
                expression = expression_base + "AND " + query

            arcpy.SelectLayerByAttribute_management(name_lyr, "NEW_SELECTION", expression)
            arcpy.CopyFeatures_management(name_lyr, out_copy)
            arcpy.AddIndex_management(out_copy, self.name_ID, self.name_ID, "UNIQUE", "ASCENDING")

        return 
Example #2
Source File: mapmatcher.py    From mapmatching with MIT License 7 votes vote down vote up
def getpointMatches(points, path):
    qr =  '"OBJECTID" IN ' +str(tuple(path))
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    opta = []
    for point in points:
        sdist = 100000
        candidate = ''
        cursor = arcpy.da.SearchCursor('segments_lyr', ["OBJECTID", "SHAPE@"])
        for row in cursor:
            #compute the spatial distance
            dist = point.distanceTo(row[1])
            if dist <sdist:
                sdist=dist
                candidate = row[0]
        opta.append(candidate)
    del cursor
    #print str(candidates)
    return opta 
Example #3
Source File: mapmatcher.py    From mapmatching with MIT License 7 votes vote down vote up
def getpointMatches(points, path):
    qr =  '"OBJECTID" IN ' +str(tuple(path))
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    opta = []
    for point in points:
        sdist = 100000
        candidate = ''
        cursor = arcpy.da.SearchCursor('segments_lyr', ["OBJECTID", "SHAPE@"])
        for row in cursor:
            #compute the spatial distance
            dist = point.distanceTo(row[1])
            if dist <sdist:
                sdist=dist
                candidate = row[0]
        opta.append(candidate)
    del cursor
    #print str(candidates)
    return opta 
Example #4
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def exportPath(opt, trackname):
    """
    This exports the list of segments into a shapefile, a subset of the loaded segment file, including all attributes
    """
    start_time = time.time()
    opt=getUniqueList(opt)
    qr =  '"OBJECTID" IN ' +str(tuple(opt))
    outname = (os.path.splitext(os.path.basename(trackname))[0][:9])+'_pth'
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    try:
        if arcpy.Exists(outname):
            arcpy.Delete_management(outname)
        arcpy.FeatureClassToFeatureClass_conversion('segments_lyr', arcpy.env.workspace, outname)
        print("--- export: %s seconds ---" % (time.time() - start_time))
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])

        # If using this code within a script tool, AddError can be used to return messages
        #   back to a script tool.  If not, AddError will have no effect.
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname)
        #raise arcpy.ExecuteError
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))

    # Return any other type of error
    except:
        # By default any other errors will be caught here
        #
        e = sys.exc_info()[1]
        print(e.args[0])
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname) 
Example #5
Source File: mapmatcher.py    From mapmatching with MIT License 6 votes vote down vote up
def exportPath(opt, trackname):
    """
    This exports the list of segments into a shapefile, a subset of the loaded segment file, including all attributes
    """
    start_time = time.time()
    opt=getUniqueList(opt)
    qr =  '"OBJECTID" IN ' +str(tuple(opt))
    outname = (os.path.splitext(os.path.basename(trackname))[0][:9])+'_pth'
    arcpy.SelectLayerByAttribute_management('segments_lyr',"NEW_SELECTION", qr)
    try:
        if arcpy.Exists(outname):
            arcpy.Delete_management(outname)
        arcpy.FeatureClassToFeatureClass_conversion('segments_lyr', arcpy.env.workspace, outname)
        print("--- export: %s seconds ---" % (time.time() - start_time))
    except Exception:
        e = sys.exc_info()[1]
        print(e.args[0])

        # If using this code within a script tool, AddError can be used to return messages
        #   back to a script tool.  If not, AddError will have no effect.
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname)
        #raise arcpy.ExecuteError
    except arcpy.ExecuteError:
        arcpy.AddError(arcpy.GetMessages(2))

    # Return any other type of error
    except:
        # By default any other errors will be caught here
        #
        e = sys.exc_info()[1]
        print(e.args[0])
        arcpy.AddError(e.args[0])
        arcpy.AddError(arcpy.env.workspace)
        arcpy.AddError(outname) 
Example #6
Source File: arcapi.py    From arcapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
def to_points(tbl, out_fc, xcol, ycol, sr, zcol='#', w=''):
    """Convert table to point feature class, return path to the feature class.

    Required:
    tbl -- input table or table view
    out_fc -- path to output feature class
    xcol -- name of a column in tbl that stores x coordinates
    ycol -- name of a column in tbl that stores y coordinates
    sr -- spatial reference for out_fc
        sr can be either arcpy.SpatialReference object or a well known id as int

    Optional:
    zcol -- name of a column in tbl that stores y coordinates, default is '#'
    w -- where clause to limit the rows of tbl considered, default is ''

    Example:
    >>> t = 'c:\\foo\\bar.shp'
    >>> o = 'c:\\foo\\bar_pts.shp'
    >>> table_to_points(t, o, "XC", "YC", 4326, zcol='#', w='"FID" < 10')
    >>> table_to_points(t, o, "XC", "YC", arcpy.SpatialReference(27700))
    >>> table_to_points(t, o, "XC", "YC", arcpy.describe(tbl).spatialReference)
    """
    lrnm = tstamp('lr', '%m%d%H%M%S', '')
    if type(sr) != arcpy.SpatialReference:
        sr = arcpy.SpatialReference(sr)
    lr = arcpy.MakeXYEventLayer_management(tbl, xcol, ycol, lrnm, sr, zcol).getOutput(0)
    if str(w) not in ('', '*'):
        arcpy.SelectLayerByAttribute_management(lr, "NEW_SELECTION", w)
    out_fc = arcpy.CopyFeatures_management(lr, out_fc).getOutput(0)
    dlt(lr)
    return (arcpy.Describe(out_fc).catalogPath) 
Example #7
Source File: arcpy_analysis.py    From pyspatialopt with MIT License 6 votes vote down vote up
def reset_layers(*args):
    """
    Clears the selection and definition query applied to the layers
    :param args: (Feature Layers) The feature layers to reset
    :return:
    """
    for layer in args:
        arcpy.SelectLayerByAttribute_management(layer, "CLEAR_SELECTION")
        layer.definitionQuery = ""