Home arrow GIS Data & Resources arrow Scripts and Code arrow Python arrow Python! Populate Numeric Field with Unique IDs
Python! Populate Numeric Field with Unique IDs PDF Print E-mail

Written by Kevin Bell,


Test this out on a dummy feature class and see if it behaves as expected. The expected behavior is that you'll end up with incremented Numeric ID's in a string field, even if some of the records already have ID's. This script should find the last used ID, and then start adding new ones. As with all of my code, look before you leap. I wrote this awhile ago for a specific task and haven't really revisited it.

#PKgenerator.py
#Purpose: find the last used numeric ID, and add ID's that are
#             incremented till all features have ID's.
# BEWARE:  this is built to run numeric ID's into a string field... trust me, i had a good reason to write this.
#Author: Kevin Bell
#Date: June 5, 2007

import time
print time.asctime()
import arcgisscripting
gp = arcgisscripting.create()
gp.OverwriteOutput = 1

gp.Workspace = r"C:\temp"
fc = "testPK.shp"
blanks = ['', ' ']


#ooooooooooooooooooooooooooooooooooooooooooooooooooooo

def getLastPK(gp, fc):
    '''find the last used primary key '''
    searchRows = gp.SearchCursor(fc)
    searchRow = searchRows.Next()
   
    pkList = []
    while searchRows:
        if(searchRow is None):
            break
        if searchRow.myPK not in blanks:
            pkList.append(searchRow.myPK)
        searchRow = searchRows.Next()
    newList = [int(st) for st in pkList]
    newList.sort()

    lastPK = newList.pop()
    del pkList
    del newList
    return lastPK

#ooooooooooooooooooooooooooooooooooooooooooooooooooooooo

updateRows = gp.UpdateCursor(fc)
updateRow = updateRows.Next()
while updateRows:
    if(updateRow is None):
        break
    blah = updateRow.myPK
    if updateRow.myPK in blanks:
        updateRow.myPK = int(getLastPK(gp, fc)) + 1
        updateRows.UpdateRow(updateRow)
    updateRow = updateRows.Next()

print time.asctime()
print "... done"

Users' Comments  
 

No comment posted

Add your comment

16, May. 2008
 
< Prev   Next >

AGRC Contacts | UGIC Contacts

feed image feed image

Utah GIS Portal © 2009 AGRC

Optimized for