3

I cannot for the life of me persuade SelectLayerByAttribute to work (I need to automate this for a complex script). Working in ArcMap's python console on already loaded shapefile, the format below:

import arcpy
from arcpy import env
arcpy.env.workspace = r"C:/Users/.../working"
arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION", " 'ATTRIBUTE' = 'Criterion' ")

results in error:

Runtime error : ERROR 000358: Invalid expression Failed to execute (SelectLayerByAttribute).

An alternative method:

import arcgisscripting
import arcpy
gp = arcgisscripting.create(9.3)
gp.workspace = "C://...//working"
sFile = "C://...//working//shapefile.shp"
lyr = "layer"
gp.makefeatureLayer_management(sFile, lyr)
gp.toolbox = "management"
gp.SelectLayerByAttribute("layer", "NEW_SELECTION", " 'ATTRIBUTE' = 'Criterion' ")

.. selects everything, including features that don't meet the criterion!

Does anyone have any idea what's going wrong? I've read some pages on this problem, but found no solution that works here. The working directory is correct. The attribute field and criterion are correctly specified (case sensitive etc), etc. Its very confusing.

6

This should work:

arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION", ' "ATTRIBUTE" = \'Criterion\' ')

You have to take care of the escape characters.

  • 2
    How annoyingly simple! However just for clarity the right format for me is actually " \"ATTRIBUTE\" = 'Criterion' " – geotheory May 22 '13 at 11:44
4

Another variation that I used to use is:

arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION", ' "ATTRIBUTE" = ' + " 'Criterion' ")

Note how the double quotes on the field name are inside single quotes, while the single quotes on the value are inside double quotes.

However, nowadays I omit the unnecessary double quotes around the field name, and simplify it to this:

arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION", "ATTRIBUTE = 'Criterion'")
1

I struggled with a similar error but just invented this:

for myValue in myList:
    query = "\"ATTRIBUTE\" = \'" + myValue + "\'"
    arcpy.SelectLayerByAttribute_management("layer", "NEW_SELECTION", query)
    arcpy.CopyFeatures_management(layer, outputName, "", "0", "0", "0")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.