Select to view content in your preferred language

SelectLayerByAttribute nto working inside a loop

672
2
05-13-2012 06:24 PM
NickDavies
Emerging Contributor
Hi everyone,
(system is 9.3.1)
I am trying to create a script that takes in LiDAR, .las files, calculates the heights from the ground, and returns point files of user defined height categories. If you guys need it I can post the whole code, but its fairly long. The Idea is that the user types in a list of strings, for example low med and high, and then defines those heights as say less than 5, between 5 and 10 and above 10, and then gets three point files out, corresponding to each height category. This is the part of the code that is failing:

Note: name_of_hights = 'low med high'.split()
# Make a layer from the feature class
    gp.MakeFeatureLayer("test.gdb\\raster_height_point","lyr") 

    counter = 0
    while counter < len(name_of_hights):
        cat_name = str(name_of_hights[counter])
        gp.SelectLayerByAttribute("lyr", "NEW_SELECTION", " ' " + cat + " ' = ' " + cat_name + " ' ")

    # Write the selected features to a new featureclass
        path1="test.gdb\\raster_height_point_"
        path2=name_of_hights[counter]
        path=path1+path2
        
        gp.CopyFeatures("lyr", path)

        print(cat_name)
        counter=counter+1


It will fail with this:
Executing: MakeFeatureLayer test.gdb\raster_height_point lyr1 # # "POINTID POINTID VISIBLE NONE;GRID_CODE GRID_CODE VISIBLE NONE;cat cat VISIBLE NONE"
Start Time: Mon May 14 14:05:59 2012
Executed (MakeFeatureLayer) successfully.
End Time: Mon May 14 14:06:00 2012 (Elapsed Time: 1.00 seconds)

If I do this #gp.MakeFeatureLayer("test.gdb\\raster_height_point","lyr")
then it will run, however it will not ever complete the loop, it never runs print(cat_name) at the end of the loop.

If I have gp.MakeFeatureLayer("test.gdb\\raster_height_point","lyr")  and  #gp.SelectLayerByAttribute("lyr", "NEW_SELECTION", " ' " + cat + " ' = ' " + cat_name + " ' ") then the loop runs through and prints fine.

If I replace the loop with if statements and have gp.SelectLayerByAttribute("lyr", "NEW_SELECTION", " cat = low ") etc it works fine, makes the point files and everything.

cat is a category in the attributes table which has already been defined, as low med or high.

But because the number of categories needs to change I cant do it with if statements.
does anyone have any ideas as to what I have got wrong in here?

Thanks for any help you can give me
Tags (2)
0 Kudos
2 Replies
BruceNielsen
Frequent Contributor
Nick,

Try re-writing the whereclause of your select statement to: "\"cat\" = '%s'" % cat_name

Attribute names need to be enclosed in double quotes, and string values in single quotes.
0 Kudos
NickDavies
Emerging Contributor
Thanks for that Bruce, it worked grate.
0 Kudos