1

I have written the following script to iterate it as a tool for all my tables with ModelBuilder, but i have a problem wth my codeblock. I want to add a field FID to all my tables and to add the values 0,1,2,3,4... for all rows of table. Each table has different number of rows. I am using ArcGIS 10.2.2 for Desktop.

The code i have written is this.

# Import system modules
import arcpy
import os
from arcpy import env
arcpy.overwriteoutput = True

# Set environment settings
inWorkspace = arcpy.GetParameterAsText(0)
inTable = arcpy.GetParameterAsText(1)
outTable = arcpy.GetParameterAsText(2)
data_type = ""


# Set local variables
# fieldName1 
# fieldName2 
fieldName1 = "FID_1"
fieldName2 = "Same"

arcpy.AddField_management(inTable, fieldName1, "DOUBLE", "", "", "", "", "NON_NULLABLE")
arcpy.AddField_management(inTable, fieldName2, "DOUBLE", "", "", "", "", "NON_NULLABLE")

arcpy.Copy_management(inTable, outTable, data_type)

# Calculate Field FID_1
fieldname = fieldName1
expression = "getCalc(!FID_1!)"
codeblock = """def getCalc(FID_1):
    FID_1 = 1
    for row in FID_1:
       FID_1 = FID_1 + 1
       return FID_1"""
# Execute CalculateField 
arcpy.CalculateField_management(inTable, fieldname, expression, "PYTHON_9.3", codeblock)

I am newbie in Python.

3

You're in need of a global variable where you can increment your new fid_1 field as CalculateField moves from record to record. Substitute this in for your last few lines of code:

(Your first record will have a value of 0, the second will be 1, the third will be 2,...)

codeblock = """id = -1
def getCalc():
    global id
    id += 1
    return id
"""
expression = 'getCalc()'
# Execute CalculateField 
arcpy.CalculateField_management(inTable, fieldname, expression, "PYTHON_9.3", codeblock)
  • @SWynne excellent that wa the answer. And the arcpy.Copy_management(inTable, outTable, data_type) after that, but why do i need this global variable? – por.bet May 20 '15 at 23:06
  • A code block function will get called once for each record in the table. Without global, id will be -1 every time getCalc is called. global adds the variable to the outer scope, ensuring the value persists between calls to the function. – DWynne May 20 '15 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.