0

I want to check existing fields in a shapefile by ArcPy. I want to test for two fields, named "Northing" and "Easting". If both fields are present then it's okay, else if one or both of the fields are missing, then I want to find this, and add that field to the shapefile by ArcPy.

1
  • Please Edit the Question to specify how you want the fields defined (number of places left and right of the decimal) for the arcpy.AddField_management directive.
    – Vince
    Aug 26 at 21:40
1

Use ListFields with sets:

import arcpy

fc = r'C:\folder\file.shp'

all_fields = {f.name for f in arcpy.ListFields(fc)} #Create a set of all fieldnames

if {'Northing','Easting'}.issubset(all_fields):
    print 'All fields are here'
else:
    print 'Field(s) are missing'

Or simply:

all_fields = [f.name for f in arcpy.ListFields(fc)]
    
for fieldname in ['Northing','Easting']:
    if not fieldname in all_fields:
        print '{0} is missing'.format(fieldname)
1
  • You probably want to use str.upper() on the fieldname and upgrade the test strings, in case a .shp.xml isn't present to generate mixed-case aliases.
    – Vince
    Aug 26 at 21:37

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