[GIS] Selecting certain fields in layer using ArcPy

arcpyselect-by-attribute

I have a layer in geodatabase, and I want to use SelectLayerByAttribute to select certain fields in this layer.

Then, use CopyFeature to output those fields to a new shapefile.

for example:

layer = I created in gdb

selection_type = 'NEW_SELECTION'

SelectedFields = """ Field_name = 'XXXX' """

arcpy.SelectLayerByAttribute_management(layer, selection_type, SelectedFields)

But, my where_clause part always invalid.

anyone can help me get the correct SQL expression?

Best Answer

See this post: Using "IN" for SQL statement in Python

Your current code returns this for the expression: "Field = 'XXXX' "

You need this in your expression (assuming your using shapefiles): "Field"= 'XXXX'

For GDB feature class, you need this: Field = 'XXXX'

You also need a feature layer for the selection.

Try this instead of your code:

layer = I created in gdb

arcpy.MakeFeatureLayer_management(layer,"layer")

selection_type = 'NEW_SELECTION'

SelectedField = '\"Field\"' #for shapefile.  If gdb change to "Field"

Expression = SelectedField + '=' + "\'XXXX\'"

arcpy.SelectLayerByAttribute_management("layer", selection_type, Expression)
Related Question