Auto-incrementing in Python Script with ArcPy cursor?
You should use a cursor instead of field calculation to achieve this.
import arcpy
#Set variables
rec=0
workspace = "D:\\GIS\\data.gdb"
arcpy.env.workspace = workspace
table_name = "data_table"
field = "KEY_2" #Short integer field
cursor = arcpy.UpdateCursor(table_name) #There is no guarantee of order here
for row in cursor:
row.setValue(field,autoIncrement())
cursor.updateRow(row)
def autoIncrement(pStart=10,pInterval=2): #Using default values instead of setting inside function
global rec
if (rec == 0):
rec = pStart
return rec
else:
rec = rec + pInterval
return rec
Here's a simple auto incrementor that doesn't rely on global variables
def autoIncrement(start=0,step=1):
i=start
while 1:
yield i
i+=step
incrementCursor = arcpy.UpdateCursor(table_name) #There is no guarantee of order here
incrementer = autoIncrement(10,2)
for row in incrementCursor:
row.setValue(field, incrementer.next()) #Note use of next method
incrementCursor.updateRow(row)
Batteries included!!! Apparently this is already in the standard library...
import itertools
inc = itertools.count()
incrementCursor = arcpy.UpdateCursor(table_name) #There is no guarantee of order here
for row in incrementCursor:
row.setValue(field, inc.next()) #Note use of next method
incrementCursor.updateRow(row)