4

I have some Shapefiles inside one Folder and for the sake of data compression I want to delete all fields from Table of Content that can be removed (that are not required)!

What I have:

What I expect:

enter image description here

My code that is not working:

import arcpy
import os

arcpy.env.workspace = r"C:\Temp\"
fcList = arcpy.ListFeatureClasses()

for fc in fcList:
    fields = arcpy.ListFields(fc)
    for field in fields:
        delFlds = [field for field in fields if field != "FID" or field != "Shape"]
        arcpy.DeleteField_management(fc, delFlds)

I am using Python 2.7 and ArcMap 10.4.1

6

You are listing field objects with ListFields, not the field names which should be input to DeleteField. So change:

[field for field in fields if field != "FID" or field != "Shape"]

to:

[field.name for field in fields if field.name not in ("FID","Shape")]

But it is probably better to use the required property since object id and shape fields can have different names in different feature classes:

for fc in fcList:
    fields_to_delete = [field.name for field in arcpy.ListFields(fc) if not field.required]
    fields_to_delete.pop() #Keep one non-required field
    for field in fields_to_delete:
        arcpy.DeleteField_management(fc, field)
  • Hi BERA thanks for your very quick replay! However it comes an Error saying: "Feature Classes and Tables must have at least one field other than OID and Shape." – gisgis Feb 8 at 10:41
  • @gisgis ok you need to keep one then. I edited my answer. – BERA Feb 8 at 10:49
1

I usually make an explicit list of fields I want to keep, then loop through and delete any others. I don't remember where I saw this method originally, but it could have come from this discussion about keeping only certain fields.

I do like @BERA's use of field.required and would suggest using that - though I've historically listed OBJECTID, FID, SHAPE, etc. explicitly.

So for example, if you needed to keep only a field called DIMENSION and a field called RESPONSIBLE_PARTY:

keep_fields = ["DIMENSION","RESPONSIBLE_PARTY"]

fieldNameList = []
fieldObjList = arcpy.ListFields(table)

for field in fieldObjList:
    if (not field.name in keep_fields) and (not field.required):
        fieldNameList.append(field.name)

arcpy.DeleteField_management(table,fieldNameList)
  • yes but as @BERA said field names may change from a shape file to anothet one capital letters or something like that but good to know thanks for your countribution – gisgis Feb 26 at 21:59

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.