Wednesday, 6 January 2016

arcgis 10.0 - Auto-incrementing in Python Script with ArcPy cursor?


I want to autoincrement values in a field within a Python script. I've done this using Field Calculator and the code referenced here. I tried using this code in the Python script below but it is not working.


#Import modules
import os, sys
import arcpy

#Set variables
workspace = "D:\\GIS\\data.gdb"
arcpy.env.workspace = workspace
table_name = "data_table"

field = "KEY_2" #Short integer field

#This is the function I want to use on my KEY_2 field
rec=0
def autoIncrement(field):
global rec
pStart = 10
pInterval = 2
if (rec == 0):
rec = pStart

return rec
else:
rec += pInterval
return rec

field = autoIncrement()

I get a TypeError when I run this code:


Traceback (most recent call last):
File "C:\Python26\ArcGIS10.0\pythonwin\pywin\framework\scriptutils.py", line 312, in RunScript

exec codeObject in __main__.__dict__
File "D:\Python\scratch\sc3.py", line 23, in
field = autoIncrement()
TypeError: autoIncrement() takes exactly 1 argument (0 given)

I've moved things around in the script a bit but have not yet gotten my field to populate. Anyone have a suggestion?


Here's my final code, based on blord-castillo's answer:


#Import modules
import os, sys
import arcpy


#Set variables
workspace = "D:\\GIS\\data.gdb"
arcpy.env.workspace = workspace
table_name = "data_table"
field = "KEY_2" #I made this a text field
rec=0

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 += pInterval
return rec

incrementCursor = arcpy.UpdateCursor(table_name) #There is no guarantee of order here
for row in incrementCursor:
row.setValue(field, str(autoIncrement()))

incrementCursor.updateRow(row)

del incrementCursor

Answer



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

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...