1

I try to add a point xy to feature class and I want to select the latest record in table (recently added). The script runs and I don't have any error message but the tool doesn't select any thing. How can I fix this?

import arcpy
arcpy.env.workspace = r'D:\Geodatabases\BD_VOCATION.gdb '
points = r'D:\Geodatabases\BD_VOCATION.gdb\Loc_vocation'
try:
    arcpy.MakeFeatureLayer_management(points,'points_layer')    
    rows = arcpy.SearchCursor(points,'','',"OBJECTID", "OBJECTID D")    
    lst = []    
    for row in rows:    
        m = row.getValue("OBJECTID")    
        lst.append(m)    
    v = lst[0]    
    r= str(v)     
    query = """{0} = {1}""".format(arcpy.AddFieldDelimiters(points, "OBJECTID"), int(r))        
    arcpy.SelectLayerByAttribute_management("points_layer", "NEW_SELECTION", query)
except:    
    print "An error occured during selection"
0
2

Use da.SearchCursor instead of the old cursor, they are much faster. You are adding field delimiters for points when it should be 'points_lyr'`. And when using try/except you make debugging difficult since the errors are hidden.

Try:

import arcpy

arcpy.env.workspace = r'C:\GIS\ArcMap_default_folder\Default.gdb'
points = 'cpoints'

arcpy.MakeFeatureLayer_management(points,'points_layer')
oidfield = arcpy.Describe('points_layer').OIDFieldName

#https://stackoverflow.com/questions/2138873/cleanest-way-to-get-last-item-from-python-iterator
for item in arcpy.da.SearchCursor('points_layer',oidfield):
    pass

sql = """{0}={1}""".format(arcpy.AddFieldDelimiters('points_layer', oidfield), item[0])
arcpy.SelectLayerByAttribute_management("points_layer", "NEW_SELECTION", sql)

enter image description here

13
  • Might be better using a list comprehension with max(), since the greatest fid value isn't required to be the last returned (unless and ORDER BY is provided, then you could slice it) – Vince May 1 '20 at 13:42
  • Thank you very match I'm just a beginner in arcpy. I would appreciate your help in finding a solution. but just one last thing the script runs pretty well in python console in Arcmap but it fails in Pyscripter!!! any help please – Fakher Rouatbi May 1 '20 at 13:56
  • 1
    Now your problem is completely different from your original question. – BERA May 1 '20 at 14:53
  • 1
    I'm satisfied, thank you very much for your precious help :) – Fakher Rouatbi May 1 '20 at 14:55
  • 1
    Nice. The way to say thank you here is to accept answer with the checkbox and upvote – BERA May 1 '20 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.