Select to view content in your preferred language

arcpy.da.InsertCursor help please

3861
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
1 Solution

Accepted Solutions
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

View solution in original post

0 Kudos
17 Replies
JakeSkinner
Esri Esteemed Contributor
Hi Tony,

Since you are working with a Personal Geodatabase, you will not need to start an edit session.  Try the following:

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

        list = []
        with arcpy.da.SearchCursor(fc, ["Address_ID"]) as cursor:
            for row in cursor:
                list.append(row[0])

        del cursor
        
        list.sort()
        Address_ID = list[-1] + 1

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

        for row in row_values:
            cursor.insertRow(row)

        del cursor

        arcpy.RefreshActiveView()
0 Kudos
TonyAlmeida
MVP Regular Contributor
JSkinns3, Thanks for your repose.

I have tried the following with out any success...
No point was created an X & Y field were not updated and AddressID was not populated.
I noticed that there was no arcpy.pointgeometry, Don't i need this to create a point feature?
On the Address ID field i need the auto sequential to start with CC and be 5 numberic numbers,
example: CC02336

def onMouseDownMap(self, x, y, button, shift):
        
        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()
        
        fc = "points"
        arcpy.env.workspace = r"C:\Temp\test.mdb"

        list = []
        with arcpy.da.SearchCursor(fc, ["Address_ID"]) as cursor:
            for row in cursor:
                list.append(row[0])

        del cursor
        
        list.sort()
        Address_ID = list[-1] + 1

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

        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
Open up the Python window in ArcMap and then execute the tool.  Any errors reported?
0 Kudos
TonyAlmeida
MVP Regular Contributor
duh that would help wouldn't...my bad.
I get this error.
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 30, in onMouseDownMap
    for row in cursor:
RuntimeError: Too few parameters. Expected 1.


with this 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, ["Address_ID"]) as cursor:
            for row in cursor:
                list.append(row[0])

        del cursor
        
        list.sort()
        Address_ID = list[-1] + 1

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

        for row in row_values:
            cursor.insertRow(row)

        del cursor

              
        # Stop the edit operation.
        edit.stopOperation()

        # Stop the edit session and save the changes
        edit.stopEditing(True)

        arcpy.RefreshActiveView()
        pass
    

0 Kudos
JakeSkinner
Esri Esteemed Contributor
Do you have the field 'Address_ID' in the feature class?
0 Kudos
TonyAlmeida
MVP Regular Contributor
actually it's AddressID. my bad...

I mad the changes to replace the Address_ID to AddressID and i am getting the following
Traceback (most recent call last):
  File "C:\Users\talmeida\AppData\Local\ESRI\Desktop10.1\AssemblyCache\{BB229966-100D-4482-A3FE-B298BD262597}\AddPoints_addin.py", line 36, in onMouseDownMap
    AddressID = list[-1] + 1
TypeError: coercing to Unicode: need string or buffer, int found
0 Kudos
JakeSkinner
Esri Esteemed Contributor
Since AddressID is a text field, you will have to convert it to an int, add 1, then convert it back to a string.  Replace:

AddressID = list[-1] + 1


with:

AddressID = int(list[-1].strip('CC0')) + 1
AddressID = 'CC0' + str(AddressID)
0 Kudos
TonyAlmeida
MVP Regular Contributor
interesting i was going about it the wrong way.

The auto sequential ends at CC09, even after adding more points the rest are CC09.
With the current code the AddressID field is populated like this CC01, CC02.
I need them have leading zeros of five like so. They don't all start at CC00001
CC00001, CC00002, CC00010, CC00123, CC01234, CC56560
Is this possible and if so how?

Thanks again for all your help!
0 Kudos
JakeSkinner
Esri Esteemed Contributor
In your case, you need every added point to be greater than the largest AddressID, i.e. CC56560?  If that is the case, what is the larget AddressID?

Or, is this tool going to be used for multiple feature classes, and the AddressID varies? i.e. CC00100 is the largest for one feature class, CC032232 is the largest for another feature class
0 Kudos