0

I have a large number of archive shapefiles which need their attribute fields tidying. During their history they have gone through various merge processes, which have resulted in some of the shapefiles having duplicate attribute fields where the system has auto assigned the suffix '_1', '_2' etc to the attribute field name. The attribute fields vary between shapefiles, and so can the duplicated attributes. Therefore I am thinking a wildcard solution rather than a definitive list removal solution is the way to go.

I am looking for an arcpy script which will run through multiple shapefiles from input source folder, remove all duplicate attribute fields suffixed with _1, _2, _3 etc and save the updated shapefiles to an output folder.

I have managed to perform the required task on a single shapefile using the acrpy code below. I use the "1" as a wildcard which seems to work in removing all attribute fields with suffix of _1, and the same for *_2 and *_3 attributes:

import arcpy

fc = 'd:\\Input\\Buildings.shp

One = [f.name for f in arcpy.ListFields(fc,"*1*")]
arcpy.DeleteField_management(fc, One)

Two = [f.name for f in arcpy.ListFields(fc,"*2*")]
arcpy.DeleteField_management(fc, Two)

Three = [f.name for f in arcpy.ListFields(fc,"*3*")]
arcpy.DeleteField_management(fc, Three)

However, I understand this is very clumsy and it falls over if the input shapefile does not contain any attribute filed that contains an underscore digit suffix. So I am looking for a more elegant solution for removing these duplicated attribute fields using ArcPy.

1 Answer 1

1

regex could be used to identify the suffix without having to know what exists ahead of time, so you could do something like this:


import re

# retrieve all field names
field_names = [field.name for field in arcpy.ListFields(fc)]
drop_fields = []

for name in field_names:
    # check to see if the field name contains a literal underscore followed by
    # one or more (+) digit (\d) then the end of the string ($).  if so, append
    # it to another list.
    if re.search(r'_\d+$', name):
        drop_fields.append(name)

# if there are any fields in the resulting list then delete them all at once 
if drop_fields:
    arcpy.DeleteField_management(fc, drop_fields)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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