Search code examples
pythonselectarcgisarcpy

arcpy query not working


I have an ArcPy script that is meant to select the desired attributes (both E-dom and E-subdom – see example below) from an attribute table based on a query.

myQuery = '"VM_POLY" = \'E-dom\'' or '"VM_POLY" = \'E-subdom\''
myInputShapeFile = r"D:\FieldStudy.shp"
myOutputShapefile = r"D:\Endangered.shp"

arcpy.Select_analysis(myInputShapeFile, myOutputShapefile, myQuery)

When the script is finished, only one type of attribute from the query is selected. In the attribute table for myInputShapeFile, there is both E-dom and E-subdom attributes, but the script will only return E-dom in the myOutputShapefile. I know the problem is possibly in the query (myQuery) but I am not sure how to resolve it.

If someone could provide some guidance, it would greatly be appreciated.


Solution

  • Could it be that you got your apostrophes wrong?

    myQuery = '"VM_POLY" = \'E-dom\'' or '"VM_POLY" = \'E-subdom\''
    #         ^             ¨      ¨^    ^             ¨         ¨^
    

    (Apostrophes marked by a ^ delimit a Python string; those marked with ¨ are escaped and therefore part of the string.)

    I suppose your query ought to be:

    myQuery = '"VM_POLY" = \'E-dom\' or "VM_POLY" = \'E-subdom\''
    #         ^             ¨      ¨                 ¨         ¨^
    

    because the or should not be interpreted by Python (logical operator applied to two strings), but should be part of the query text.