Question

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.

Was it helpful?

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.

OTHER TIPS

Python string formatting (and the SQL "IN" operator) make it (slightly) easier to handle the complex quote syntax:

myQuery = "\"{}\" IN ('{}', '{}')".format("VM_POLY", "E-dom", "E-subdom")

I would simplify your query with specifiers.

myQuery = ' "%s" = %s or "%s" = %s ' %('VM_POLY','E-dom','VM_POLY','E-subdom')

I know it seems quirky at first but its a good way to ensure your quotes and double quotes are positioned correctly for such things that require specific formatting. They have become my best friend as of late.

NOTE: if you have numbers you would like to inject into the string you can do so by using %d instead of %s.

Try this:

myQuery = '"VM_POLY" = "E-dom" or "VM_POLY"= "E-subdom"'

As was stated the or operator was being mishandled because it was not within the confines of your quotation. You also had the escape character \ in there which probably was not needed but you were attempting to work around the fact that your or operator was exposed and not part of the SQL query and thus picked up by the Python interpreter instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top