[GIS] Accessing attribute table within shapefile and replace values

arcgis-10.0arcpycursor

I would like to find a Python script that will access an attribute table within a shapefile and either update or replace records inside a field column. More specifically, I would like to use the replace expression to convert a table record like "123-456-789" to "123456789". I have many records to process and would like the best approach to do this task using Python.

Best Answer

What you need is an UpdateCursor.

The UpdateCursor function creates a cursor that lets you update or delete rows on the specified feature class, shapefile, or table. The cursor places a lock on the data that will remain until either the script completes or the update cursor object is deleted.

Your code would look something like the following:

import arcpy

# Create update cursor for feature class 
# 
rows = arcpy.UpdateCursor("path_to_your_data_here") 

for row in rows:
    # Fields from the table can be dynamically accessed from the row object.
    #   Here, the field is named targetField as I don't know your field name
    targetRow = row.targetField #Assigns value of targetField to string
    row.targetField = targetRow.translate(None, '-') #Removes the dashes
    rows.updateRow(row) 

# Delete cursor and row objects to remove locks on the data 
# 
del row 
del rows

If you don't have ArcPy, you can use dbfpy to directly access and edit the attributes in the shape file's dbf file. The syntax is rather simple:

from dbfpy import dbf

db = dbf.Dbf("your_file.dbf")

#Editing a value, assuming you want to edit the first field of the first record
rec = db[0]
rec["FIRST_FIELD"] = "New value"
rec.store()
del rec
db.close()
Related Question