8

Im trying to write a script that finds out if the shapefile has a specific field and if not to add the field. I get it to show me the field, but the loop goes through each field, so it would create a new field each time the specified field is not there. But if it's theres I just want it to say it is there and if it's not to create new field. My code so far just says:

"not filled in yet"
"not filled in yet"
"not filled in yet"
"cities.shp"
"not filled in yet"

(prints out like this cause there are five fields)

My code so far:

fieldList = arcpy.ListFields("cities.shp")

for field in fieldList:

if field.name == "CAPITAL":
    print "cities.shp"

else: 
    "then add new field"
1
  • 1
    Does that code really match that output. I'm not familiar with arcpy, but it seems highly dubious.
    – BradHards
    Commented Nov 12, 2013 at 6:09

1 Answer 1

10

Instead of looping over the current field names, you can loop over the field names you want to add. Let's say you have a list, to_add, containing the field names you want your feature class to have. You can then use the in statement to check if each item from to_add is in fieldList. The following should work:

#List of field names to be added
to_add = ["Area", "Date_add", "User_add", "etc."]

#Create a list of existing field names
fieldList = arcpy.ListFields("cities.shp")    
fieldName = [f.name for f in fieldList]

for field in to_add:
  if field in fieldName:
    print "Already exists!"
  else:
    arcpy.AddField_management("cities.shp", field, "TEXT")

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.