2

I have a list of files that need to be present in my featureclasses - myFields[]. I need to add these fields if they are not present in my FeatureClasses.

import arcpy

myField="Field01"
myFields = [field01, field02, field03]

env.workspace = "D:/test/data.gdb"
fcs = arcpy.ListFeatureClasses()

for f in fcs:
    fieldList = arcpy.ListFields(f)
    for field in fieldList:   
         if field.name == myField:
             arcpy.AddField_management(fc, myField, "TEXT")

This works when I only have one field, but I have a list of fields! How do I adapt this when I have many fields and many different formats? Do I have to write a separate function for each field, or is there a cool python way of doing this?

closed as unclear what you're asking by PolyGeo Oct 15 '16 at 7:16

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

0

I've run out of time to get this working but hopefully this will give you some ideas of the Python coding necessary to write your script:

import arcpy

myField="Field01"
myFields = [field01, field02, field03]

env.workspace = "D:/test/data.gdb"
fcs = arcpy.ListFeatureClasses()

for f in fcs:
    fieldList = arcpy.ListFields(f)
    for field not in fieldList:
        for myField in myFields:
            if field.name == myField:
                if field.type == "String":
                    arcpy.AddField_management(fc, myField, "TEXT")
                elif field.type == "SmallInteger":
                    ...
                elif ... :
                    ...
                else:
                    print "Field type of {0} is not yet handled".format(field.type)

You just needed to create another for loop inside your second one. This is Python rather than ArcPy so I recommend using both Stack Overflow (for Python) and GIS SE (for ArcPy) when researching your questions.

If your fields are not all of type text, then field objects have a type property that you can use with if/elif/else statements to alter the type of field you add.

  • Is good for fields with just text, but what if field01 = int and Field02 = Date and Field03 = Long? – Robert Buckley Jun 17 '15 at 10:03
  • Field objects have a type property so you just need to use that with if/elif/else statements to alter the type of field you add. – PolyGeo Jun 17 '15 at 10:07
  • Sorry. I´ve made a mistake.If I use " if field.name == myField " then I would be adding a field which has is already present. I need the opposite. If field.name != myField - but in this case I have the problem that I have to compare 2 lists. – Robert Buckley Jun 17 '15 at 11:00

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