Did your SearchCursor read at least one record?

Blog Post created by Leandermen on Jan 14, 2015

I have the same question the other day when i was developing a map automation script.


To give you some context, I have to query a table and copy a single record's data into multiple Layout Elements. If you work with a SearchCursor, the third parameter it's a WHERE statement, you can use it to retrieve a single record data with the correct query. I used it to retrieve data from a GDB table, but what if my WHERE statement returns zero records. The cursor is still working and no sings of error were detected in test environment, i just noticed that my Layout elements doesn't update with the table data (of course there's no data that my statement could give me).


So i decided to create a validation to check when i create my SearchCursor that it contains data that i can lookup.


The solution it's quite simple i defined a little python function called ValidateSearchCursor which counts my records of a SearchCursor Input and if it returns zero, the function returns false.


def ValidateSearchCursor(cursor):
     counter = 0
     for record in cursor:
          counter += 1;
     cursor.reset() #Don't forget it. Reset the cursor to use it again later in your script
     if counter != 0:
          return True;
          return False;


SIMPLE BUT EFFECTIVE!! and easy to move and to add into your libraries


See you next time!! Don't forget to follow me Leandro Zamudio León i appreciate your feedback and if you want more tips like this...


Until the next Coffee Time