Select to view content in your preferred language

arcpy.da.InsertCursor help please

3860
17
Jump to solution
02-10-2014 01:08 PM
TonyAlmeida
MVP Regular Contributor
I am trying to create a script that will create a new point feature to a point feature class, but also add the x, y coordinets to "X_Coord" and "Y_Coord" fields. The following code sort of works but only populates the "X_Coord" field. I can't seem to get it to populate the "Y_Coord" field.

works but only populates the "X_Coord" field.
import arcpy import pythonaddins import os from arcpy import env  class Add_points(object):     """Implementation for AddPoints_addin.Add_points (Tool)"""     def __init__(self):         self.enabled = True         self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.     def onMouseDownMap(self, x, y, button, shift):         fc = "points"         workspace = r"C:\Temp\test.mdb"         arcpy.env.overwriteOutput = True          # Start an edit session. Must provide the worksapce.         edit = arcpy.da.Editor(workspace)          # Edit session is started without an undo/redo stack for versioned data         #  (for second argument, use False for unversioned data)         edit.startEditing(True)          # Start an edit operation         edit.startOperation()                  mxd = arcpy.mapping.MapDocument("Current")         df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]         lyr = arcpy.mapping.ListLayers(mxd, "points")[0]          #message = "Your mouse clicked:" + str(x) + ", " + str(y)         #pythonaddins.MessageBox(message, "My Coordinates")                           point = arcpy.Point(x, y)         pointGeometry = arcpy.PointGeometry(point)         row_value = ((x, y))         cursor = arcpy.da.InsertCursor(fc, ("X_Coord", "SHAPE@XY"))         cursor.insertRow(row_value)         """ Create a copy of the PointGeometry objects, by using pointGeometry  """         """  as input to the CopyFeatures tool. """         arcpy.CopyFeatures_management(pointGeometry, r"C:\Temp\test.mdb")          # Stop the edit operation.         edit.stopOperation()          # Stop the edit session and save the changes         edit.stopEditing(True)           arcpy.RefreshActiveView()         pass      



I have tried the following but nothing happens, no point feature is created and the "X_Coord" and "Y_Coord" fields are not populated.
import arcpy import pythonaddins import os from arcpy import env  class Add_points(object):     """Implementation for AddPoints_addin.Add_points (Tool)"""     def __init__(self):         self.enabled = True         self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.     def onMouseDownMap(self, x, y, button, shift):         fc = "points"         workspace = r"C:\Temp\test.mdb"         arcpy.env.overwriteOutput = True          # Start an edit session. Must provide the worksapce.         edit = arcpy.da.Editor(workspace)          # Edit session is started without an undo/redo stack for versioned data         #  (for second argument, use False for unversioned data)         edit.startEditing(True)          # Start an edit operation         edit.startOperation()                  mxd = arcpy.mapping.MapDocument("Current")         df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]         lyr = arcpy.mapping.ListLayers(mxd, "points")[0]          #message = "Your mouse clicked:" + str(x) + ", " + str(y)         #pythonaddins.MessageBox(message, "My Coordinates")          Fields = ["X_Coord", "Y_Coord", "SHAPE@XY"]                          point = arcpy.Point(x, y)         pointGeometry = arcpy.PointGeometry(point)         row_value = ((x, y))         cursor = arcpy.da.InsertCursor(fc, (Fields))         cursor.insertRow(row_value)         """ Create a copy of the PointGeometry objects, by using pointGeometry  """         """  as input to the CopyFeatures tool. """         arcpy.CopyFeatures_management(pointGeometry, r"C:\Temp\test.mdb")          # Stop the edit operation.         edit.stopOperation()          # Stop the edit session and save the changes         edit.stopEditing(True)           arcpy.RefreshActiveView()         pass 


and if possible i would like it to populate an auto sequential number based on the last highest number. The field i need the sequential number is a field called the Address_ID field.
Tags (2)
0 Kudos
17 Replies
TonyAlmeida
MVP Regular Contributor
This tool would only be used for one feature class. yes i need every newly add point to generate a new number based off the last highest number in the AddressID field. The current largest number is CC18417.
I was thinking that some how i would sort the AddressID field to get the highest value, then update the values
from the last highest AddressID.
0 Kudos
JakeSkinner
Esri Esteemed Contributor
What you need to do is strip 'CC' from the AddressID and then convert the value to an integer before appending it to the list.  You can then sort the list, select the last value, add one and then append 'CC' back to this value.  Ex:

def onMouseDownMap(self, x, y, button, shift):   
    arcpy.env.workspace = r"C:\Temp\test.mdb"
    fc = "points"

    list = []
    with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:
        for row in cursor:
            list.append(int(row[0].strip("CC")))        
    del cursor

    list.sort()
    AddressID = list[-1] + 1
    AddressID = 'CC' + str(AddressID)

    row_values = [(x, y, (x, y), AddressID)]
    cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])

    for row in row_values:
        cursor.insertRow(row)
    del cursor

    arcpy.RefreshActiveView()
0 Kudos
TonyAlmeida
MVP Regular Contributor
The only issues with stripping the "CC" from the AddressID field is that there are other alphabetic letters like "NA", "CA" but i don't do anything with those, i am just interested in the attributes with "CC". I should have mentioned that before, my bad. but that's why i was thinking of maybe doing to the cursor twice, first to sort and get the highest AddressID value then to populate the AddressID.
I saw a post a while back that had something similar to what i am talking about but of course i can't find now.

I tested the code you provided and i noticed that this error, i believe it was because i had some points that were NULL in the AddressID field.
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 31, in onMouseDownMap
    list.append(int(row[0].strip("CC")))
ValueError: invalid literal for int() with base 10: ''
0 Kudos
TonyAlmeida
MVP Regular Contributor
Is there a way to by pass the existing feature with Null in the AddressID?
How do i by pass the features with NA and CC?
0 Kudos
JakeSkinner
Esri Esteemed Contributor
You can add an IF statement.  Ex:

with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:
        for row in cursor:
            if "CC" in row[0]:
                list.append(int(row[0].strip("CC")))        
del cursor
0 Kudos
TonyAlmeida
MVP Regular Contributor
JSkinns i have applied you code but i am still not able to get passed the Null or empty AddressID feature.
as you can see on the pic i have attached the last point feature didn't have anything in the AddressID field.
I would like it to bypass this and continue populate the AddressID for the next feature.

Current code.
import arcpy
import pythonaddins
import os
from arcpy import env

class Add_points(object):
    """Implementation for AddPoints_addin.Add_points (Tool)"""
    def __init__(self):
        self.enabled = True
        self.cursor = 3 # Can set to "Line", "Circle" or "Rectangle" for interactive shape drawing and to activate the onLine/Polygon/Circle event sinks.
    def onMouseDownMap(self, x, y, button, shift):
        
        arcpy.env.overwriteOutput = True

        # Start an edit session. Must provide the worksapce.
        edit = arcpy.da.Editor(env.workspace)

        # Edit session is started without an undo/redo stack for versioned data
        #  (for second argument, use False for unversioned data)
        edit.startEditing(True)

        # Start an edit operation
        edit.startOperation()

        fc = "points"
        arcpy.env.workspace = r"C:\Temp\test.mdb"

        list = []
        with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:
            for row in cursor:
                list.append(int(row[0].strip("CC")))        
        del cursor

        list.sort()
        AddressID = list[-1] + 1
        AddressID = 'CC' + str(AddressID)

        row_values = [(x, y, (x, y), AddressID)]
        cursor = arcpy.da.InsertCursor(fc, ["X_Coord", "Y_Coord", "SHAPE@XY", "ADDRESSID"])

        for row in row_values:
            cursor.insertRow(row)
        del cursor

        arcpy.RefreshActiveView()
        
        # Stop the edit operation.
        edit.stopOperation()

        # Stop the edit session and save the changes
        edit.stopEditing(True)        
        pass
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Try the following:

with arcpy.da.SearchCursor(fc, ["AddressID"]) as cursor:     for row in cursor:         try:             if "CC" in row[0]:                 list.append(int(row[0].strip("CC")))         except TypeError:             pass del cursor
0 Kudos
TonyAlmeida
MVP Regular Contributor
JSkinns that worked perfectly!
Now if i can only get to work with SQL express database.
I posted my problem here but i haven't had a response.
http://forums.arcgis.com/threads/102661-Setting-workspace-Q

thank you so much.
0 Kudos