I need to use arcpy.Select_analysis()
in my arcpy script, but I have problem with using variables. When I use hard coded values in where_clause, it is working.
where_clause = '"Area" > 20'
arcpy.Select_analysis("input", "output", where_clause)
When I try to use variables in where_clause because user of toolbox will enter name of field and value of minimimum area, there is always problem with invalid expression. I tried lots of types of expressions, but nothing is working.
field_area = "Area"
minimum_area = 20
where_clause = 'field_area > minimum_area'
arcpy.Select_analysis("input", "output", where_clause)
Error:
Runtime error Traceback (most recent call last): File "", line 1, in File "c:\program files (x86)\arcgis\desktop10.2\arcpy\arcpy\analysis.py", line 98, in Select raise e ExecuteError: ERROR 000358: Invalid expression field_area> minimum_area Failed to execute (Select).
I work in ArcMap 10.2.
1 Answer 1
The problem is that you're not using variables in your query. Instead you're using strings that happen to be the same as your variable names.
What you want is:
field_area = 'Area'
minimum_area = 20
where_clause = '{} > {}'.format(arcpy.AddFieldDelimiters('input', field_area), minimum_area)
arcpy.Select_analysis("input", "output", where_clause)
Of course, that's assuming that 'input' is the name of your feature class--as in your supposedly working example above. However, I would strongly recommend that you assign the feature class name to a variable instead:
field_area = 'Area'
minimum_area = 20
fcInput = 'ThePathAndOrNameOfMyFeatureClass'
fcOutput = 'ThePathAndOrNameOfTheOutputFeatureClass'
where_clause = '{} > {}'.format(arcpy.AddFieldDelimiters(fcInput, field_area), minimum_area)
arcpy.Select_analysis(fcInput, fcOutput, where_clause)
-
3+1 for using .format -- String math is too convoluted when true formatting is available. I wish I could give another plus-up for non-ambiguous variable naming.Vince– Vince2016年03月14日 17:50:41 +00:00Commented Mar 14, 2016 at 17:50
'
. Not tested, but try this:where_clause = '"' + field_area + '" > ' + "'" + str(minimum_area) + "'"