Wednesday, 20 May 2015

select by attribute - Runtime error : ERROR 000358: Invalid expression using SelectLayerByAttribute in ArcPy?


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.



Answer



This should work:


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

You have to take care of the escape characters.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...