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

2 Answers 2

11

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)
2
  • Hi, Do you know why one non-required field is needed? It looks like it won't work if one non-required field is not kept. Commented Jun 29, 2023 at 2:48
  • 1
    Hi, no I dont know why
    – Bera
    Commented Jun 30, 2023 at 8:33
2

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)
1
  • 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
    Commented Feb 26, 2019 at 21:59

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.