Make feature layer & Select by attribute

718
3
06-28-2010 03:14 AM
Andreas_ForøTollefsen
New Contributor
Hi all.

I need to loop and split a polygon shapefile using a list of values that i want to incorporate into my query.
However, I cannot get the query to work properly.
How can i use variable x in the query?

Thanks.

# Import system modules
import sys, string, os, arcgisscripting

# Create the Geoprocessor object
gp = arcgisscripting.create()
gp.overwriteoutput = 1

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Set workspace
gp.workspace = "C:\\geodata\\PRIO_GRID\\Data_Sources\\cShapes0.24\\"

# Create list
yearlist = list(range(1946, 2009))

# Process: Select Layer By Attribute...
for x in yearlist:
    gp.MakeFeatureLayer("cshapes.shp","lyr")
    gp.SelectLayerByAttribute("lyr", "new_selection", "\"gwsyear\" <= x AND \"gweyear\" >= x")
    gp.CopyFeatures("lyr", "cshapes"+x)
    
0 Kudos
3 Replies
RDHarles
Occasional Contributor
How/Where are you setting variables gwsyear & gweyear?
Is it possible you are setting them as a string instead of a number?
0 Kudos
ChrisMathers
Occasional Contributor III
The problem is that the geoprocessor isnt looking at that x as a variable, just a part of the query string. Build your query outside of that tool and just make the query string a variable. You dont need to escape every quote in the geoprocessing tools, its better to use string literals when making an input variable like this. You may have to convert your date into strings if they are stored as integers so that the string can concatenate.

 
Query=r'""qwsyear" <= ' + str(x) + r' AND "gweyear" >= ' + str(x) + r'"'
 
gp.SelectLayerByAttribute("lyr", "new_selection", Query)
 
 
>>> x=1957
>>> query=r'""qwsyear" <= ' + str(x) + r' AND "gweyear" >= ' + str(x) + r'"'
>>> query
'""qwsyear" <= 1957 AND "gweyear" >= 1957"'
0 Kudos
Andreas_ForøTollefsen
New Contributor
Great. That worked.

Here is my code:


# Import system modules
import sys, string, os, arcgisscripting

# Create the Geoprocessor object
gp = arcgisscripting.create(9.3)
gp.overwriteoutput = 1

# Load required toolboxes...
gp.AddToolbox("C:/Program Files/ArcGIS/ArcToolbox/Toolboxes/Data Management Tools.tbx")

# Set workspace
gp.workspace = "C:\\geodata\\PRIO_GRID\\Data_Sources\\cShapes0.24\\"

# Create list
yearlist = list(range(1946, 2009))

# Define emptygrid
emptygrid = "C:\\geodata\\PRIO_GRID\\Data_Sources\\EmptyGrid\\emptygrid230610_WGS.shp"

# Select cShapes year and copy each year to new shapefile
for x in yearlist:
    query ="GWSYEAR <= " + str(x) + " " + "AND" + " " + "GWEYEAR >= " + str(x)
    gp.MakeFeatureLayer("cshapes.shp","lyr")
    gp.SelectLayerByAttribute("lyr", "new_selection", query)
    gp.CopyFeatures("lyr", "cshapes"+str(x))
    
del yearlist, query, x, emptygrid
print "completed"
0 Kudos