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.
4 Answers
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()
Alternatively and very straight forward you could also open the dbase table (dbf) coming with your shape in excel or libreoffice calc. They should be full editable and therefore you can simply remove all dashes in multiple columns.
You may also use Field Calculator with Python expression !Field!.replace('-','')
.
-
-
1OP say that he have many records to convert, but does not specify if he needs to do more than one .shp file or even fields, so simplest answer is to use Field Calculator rather than writing script with update cursor. Its good to know that translate would work faster than replace method.– TomekDec 27, 2012 at 10:22
I would use a data access module da
Update Cursor and the replace()
method to accomplish this. The following is the preferred (new) method of using an Update Cursor.
import arcpy
shp = r'C:\path\to\shapefile.shp'
with arcpy.da.UpdateCursor(shp, "your_field") as cursor:
for row in cursor:
row[0].replace("-", "")
cursor.updateRow(row)