The code below deletes fields I deem unnecessary (those not defined in 'keepFields') as I would like it to.

def EnvCompliance_Del(Workspace):
    env.workspace = Workspace
    Fields = arcpy.ListFields('aFeatureClass')
    keepFields = ['Field_A', 'Field_B', 'Field_C')
    in_table = 'aFeatureClass' + '.dbf'  
    drop_fields = [x.name for x in Fields if x.name not in keepFields]
    arcpy.DeleteField_management(in_table, drop_fields)


When there are no extra fields, however, I receive an error message that states:

raise e ExecuteError: Failed to execute. Parameters are not valid. ERROR 000735: Drop Field: Value is required Failed to execute (DeleteField).

What can I add so that code prints some message stating something similar to "no unnecessary fields within 'aFeatureClass' exist" rather than the error message. My initial thought is an if-else statement, where the 'else' portion prints the message, but I am unable to successfully incorporate it.


You can skip the drop fields if no drop fields are present:

drop_fields = [x.name for x in Fields if x.name not in keepFields]
if len(drop_fields) >0: arcpy.DeleteField_management(in_table, drop_fields)
else: print("No Extra Fields Found")
  • 1
    Empty lists in Python are treated as False, so the expression can be simplified to if drop_fields: <code> – Paul Dec 28 '16 at 2:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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