[GIS] arcpy Make Feature Layer using a where clause

arcgis-desktoparcpywhere-clause

From a table of lines and polylines I am I'm building a seperate table of points (nodes) with their X and Y coordinates stored as attributes. I want the nodes to be unique, so I'm checking to see if a node with the same coordinates has already been inserted by making a feature layer from the nodes table with a SQL clause to selecting any rows with the same coordinates. If the feature layer has zero rows then I insert the new node otherwise I do nothing and move to the next line/polyline.

The problem I have is that the SQL clause in the Make Feature Layer seems to be selecting rows even where the coordinates do not match. It works fine for the first one but then after that it picks 1 row each time when most or all of the time it should pic zero rows.

This is making my head hurt. Can any one help please?

Here is the script..

import arcpy
arcpy.env.overwriteOutput = True

fc_Nodes = 'C:\Users\Rob&LP\Documents\GIS General\DRN Configuration\DRN Sample\LinkNodes_point.shp'

arcpy.DeleteRows_management(fc_Nodes)

fc_Links = 'C:\Users\Rob&LP\Documents\GIS General\DRN Configuration\DRN Sample\DRN_SevUp_14Recs_polyline.shp'

shapeName = arcpy.Describe(fc_Links).shapeFieldName

rows = arcpy.SearchCursor(fc_Links)
InCurs = arcpy.InsertCursor(fc_Nodes)

Ins = 0

for row in rows:

 feat = row.getValue(shapeName)
 ANode = feat.firstPoint


#check to see if node has already been inserted
 arcpy.MakeFeatureLayer_management(fc_Nodes, "fl_P1", """"X" = ANode.X""")
 if int(arcpy.GetCount_management("fl_P1").getOutput(0)) == 0:

  Ins = Ins + 1

  print "NumRows: " + str(arcpy.GetCount_management("fl_P1").getOutput(0))
  print "Inserted: "+ str(Ins)
  print "ANodeX: " + str(ANode.X)
  print ""


  newNode = InCurs.newRow()
  newNode.SHAPE = ANode
  newNode.setValue("CHECK", 1)
  newNode.setValue("X", ANode.X)
  newNode.setValue("Y", ANode.Y)
  newNode.setValue("ID", Ins)

  InCurs.insertRow(newNode)
  del ANode
  arcpy.Delete_management("fl_P1") 
 else:

  print "NumRows: " + str(arcpy.GetCount_management("fl_P1").getOutput(0))
  print "NOT Inserted : " + str(ANode.X)
  print ""
  del ANode
  arcpy.Delete_management("fl_P1") 

arcpy.Delete_management("fl_P1")      
del InCurs
del rows


print "--------------End---------"

`

Best Answer

Your feature layer is going to be the same for each row because you selection query """"X" = ANode.X""" is contant in your call to arcpy.MakeFeatureLayer_management. ANode.X in this string is just text, not the value of the variable. You can use the python string format command to put the value of the variable into the query string.

Something like the following should work

arcpy.MakeFeatureLayer_management(fc_Nodes, "fl_P1", """"X" = {}""".format(ANode.X))

If you want to query on X and Y, then use

arcpy.MakeFeatureLayer_management(fc_Nodes, "fl_P1", '"X" = {0} AND "Y" = {1}'.format(ANode.X, ANode.Y))
Related Question