Get Count While Applying a filter

537
3
10-14-2011 06:36 AM
ChristinaGnadinger
New Contributor II
I hope this is something easy to do, although I can't find the right formula to make this work.

I am trying to run a filter on a table to find features who have a specific field blank. I ultimately want to output that count of features out to a text file. The trouble I am having is that GetCount_management does not work correctly when I try and apply a filter to it.

Right now I have ..

filter = "\"FACILITY_I\" = ' '"
lyr = "C:\\Users\\gisadmin\\Desktop\\TEST\\FH_Test.shp"
result = int(arcpy.GetCount_management(lyr).getOutput(0))
print result 


and that works .. but it's (obviously) giving me the total since the filter is not referenced in at all. When I try and build a filter in I start getting errors, typically Runtime errors in executing tool.

Does someone know how to run this function while applying a filter, or another way to accomplish the same goal?

Also, as opposed to printing the results to a screen I'd like to write them to a table, however I'm moving from vB into Python so I'm still learning the language.

Any advice or help would be greatly appreciated. Thank you!
Tags (2)
0 Kudos
3 Replies
MarcNakleh
New Contributor III
Hello Christina,

What you need is the Make Feature Layer method. It works almost identically to Select By Attribute in ArcMap or ArcCatalog: it will use the filter and generate a layer of features that satisfied the filter condition.

filter = "\"FACILITY_I\" = ' '"
shp = r"C:\Users\gisadmin\Desktop\TEST\FH_Test.shp"
lyr = arcpy.MakeFeatureLayer(shp, filter)
result = int(arcpy.GetCount_management(lyr).getOutput(0))
print result


And your output can go wherever you want, depending on what format you're looking at. To write it to a table, you could use a Cursor object. If you're writing it to a table in a textfile or CSV, you could write it using Python's builtin open function. With a little more information, this shouldn't be hard to do.

I hope this helps!
0 Kudos
ChristinaGnadinger
New Contributor II
Thank you for your help so far! Luckily it's not erroring out on the filter, however it's not acknowledging it either. On this test set I still get 89 no matter what. I've even tried altering the filter to make sure it wasn't incorrectly typed but that is not helping.

Anyway I have it not erroring and now printing to the test file, so if I can figure out how to get the filter to work then I'll be set!

Thank you!
0 Kudos
ChristinaGnadinger
New Contributor II
I found the tweak I needed. Thank you for your help!!

shp = r"C:\Users\gisadmin\Desktop\TEST\FH_Test.shp"
filter = "\"FACILITY_I\" = ' '"
lyr = arcpy.MakeFeatureLayer_management(shp, "FH_Test_lyr", filter)
result = int(arcpy.GetCount_management(lyr).getOutput(0))
outtable.write(str(result))
print result
0 Kudos