1

I'm quite new with python and i'm currently stuck trying to make a loop... I have a shape file of a grid with several fields of different species (more than 150). The values of each record are 0 or 1 depending on the presence of the species on that grid. What i need to do is to make a selection of grids for each specie. So far this is my attempt:

import arcpy import os, sys, datetime, time arcpy.CheckOutExtension("Spatial") from arcpy.sa import * from arcpy import env arcpy.env.overwriteOutput = 1 arcpy.env.workspace = "G:\\Sara_hab_sp\\test" arcpy.env.scratchWorkspace = "G:\\temp\\default.gdb" arcpy.MakeFeatureLayer_management("G:\\Sara_hab_sp\\Confocc_pergrid.shp", "G:\\Sara_hab_sp\\test\\grid50") gridlist = arcpy.ListFields ("G:\\Sara_hab_sp\\test\\grid50") for grid in gridlist: print(grid.name) query = 'grid = 1' selectgrid50 = arcpy.SelectLayerByAttribute_management ("G:\\Sara_hab_sp\\test\\grid50", "NEW_SELECTION", query ) 

I always get an error message about the syntax of the query but i tried different things and it seems to me the error it's more related to the fact that maybe it's not possible to enter a list of fields in a query, although i have seen it's possible to do it with a list of different values of the same field...

Any suggestions on how to deal with this?

1 Answer 1

1

if you put grid in a string, it is no more the variable but ... a string. Print your query to check.

you need to build your query using the variable grid, for instance

query = '"{}" = 1'.format(grid.name) 

or (easier to read but more complex when you have many parameters)

query = '"' + grid.name + '"=1' 

note that I put some " " around the field name for the query and I assume that your fields are numeric.

The second problem is that your field list will return all field by default (including OID and geometry). You should therefore specify that you want only the integer fields

gridlist = arcpy.ListFields ("G:\\Sara_hab_sp\\test\\grid50","*","Integer") 

As a last remark, you could directly use your query with MakeFeatureLayer, this saves you one line of code (but it will depend on the rest of your code to see if it is useful or not).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.