I have many shapefiles. Each shapefile has a specific name which is the same as one of the column of data within the attribute table. For each shapefile, I would like to delete all the fields that don't have the same name as the shapefile name.

For example, shapefile might be named m_1. Within its attribute table, there will be lots of columns, which are named "gid", m_1, m_2, m_3, m_3 etc. I would like to delete all those fields except the column "gid" and "m_1". Below is my code, which doesn't work.

I'm new to programming.

import arcpy
arcpy.env.workspace = "D:\Paper"
fcList = arcpy.ListFeatureClasses()

for fc in fcList:
    field_names = []
    field_names = [f.name for f in arcpy.ListFields(fcList)]
        if field_names <> fcList:
            arcpy.DeleteField_management(fc, field_names)
  • 3
    Don't forget to take the Tour. For questions that involve code we ask that you show us where you are stuck with your own code by including a code snippet in your question. There is an edit button beneath your question which will enable you to do that and a {} button that enables you to format any highlighted code nicely.
    – PolyGeo
    Jun 7, 2017 at 22:21
  • 1
    Have a close look at the docs resources.arcgis.com/en/help/main/10.2/index.html#//… where it says drop_field the next line is [drop_field,...] which means make a python list of objects and put it in here perform this action on multiple (fields in this case). I know it's not immediately obvious but that's what it means when you see the square brackets in the help docs. You can use listfields to get all your fields and iterate through them, adding to a list, and then call one delete at the end which is much faster than deleting each field one at a time. Jun 7, 2017 at 22:24
  • Why are you keeping the field gid if you would like to delete all fields that don't have the same name as the shapefile name ? Aug 21, 2017 at 17:32

1 Answer 1


Create a list of fields for each shapefile, and exclude fields that can't/shouldn't be deleted. Those fields would be:

  • OID Field
  • shape field
  • shapefile name field

Something like this:

import arcpy
import os

arcpy.env.workspace = "D:\Paper"
fcList = arcpy.ListFeatureClasses()

for fc in fcList:
    desc = arcpy.Describe (fc)
    #shape field name
    shpFld = desc.shapeFieldName
    #oid field
    oidFld = desc.OIDFieldName
    #shapefile name field
    shpFileFld = os.path.splitext (fc) [0]
    #list fields
    delFlds = [f.name for f in arcpy.ListFields (fc)
               if not f.name in [shpFld, oidFld, shpFileFld]]

    #delete fields
    arcpy.DeleteField_managemnet (fc, delFlds)

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.