How to delete multiple fields from a list of geodatabase tables

431
2
Jump to solution
02-02-2019 01:07 PM
JohnPapageorgiou
New Contributor III

I found a script that allows the input of a feature class and then it deletes all the fields in a feature class with the exception of those listed in the "if" statement.  The script works great when passing 1 feature class or 1 file geodatabase table.  However, I need to pass a list of tables as the input, and when I do, I get the error: IOError: "[ list of all the tables I tried to enter]" does not exist.  Below is the script with my attempted modifications.  Is what I am trying to do possible?  Thank you in advance.

John

import arcpy
from arcpy import env

env.workspace = r"C:\user\test22\test_tables.gdb"
list_filename_Tables = arcpy.ListTables("*_filename*")

fc = list_filename_Tables

for f in arcpy.ListFields(fc):
  if (f.name == 'OBJECTID' or f.name == 'ID' or f.name == 'Project1' or f.name == 'Height'):
    print("cant delete {}".format(f.name))
  else:
    arcpy.DeleteField_management(fc, f.name)
0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

ListFields doesn't operate directly on a list, you need to loop/iterate over the list of feature classes.  Try:

import arcpy
from arcpy import env

env.workspace = r"C:\user\test22\test_tables.gdb"
list_filename_Tables = arcpy.ListTables("*_filename*")

for fc in list_filename_Tables:
    for f in arcpy.ListFields(fc):
        if (f.name == 'OBJECTID' or f.name == 'ID' or f.name == 'Project1' or f.name == 'Height'):
            print("cant delete {}".format(f.name))
        else:
            arcpy.DeleteField_management(fc, f.name)

View solution in original post

2 Replies
JoshuaBixby
MVP Esteemed Contributor

ListFields doesn't operate directly on a list, you need to loop/iterate over the list of feature classes.  Try:

import arcpy
from arcpy import env

env.workspace = r"C:\user\test22\test_tables.gdb"
list_filename_Tables = arcpy.ListTables("*_filename*")

for fc in list_filename_Tables:
    for f in arcpy.ListFields(fc):
        if (f.name == 'OBJECTID' or f.name == 'ID' or f.name == 'Project1' or f.name == 'Height'):
            print("cant delete {}".format(f.name))
        else:
            arcpy.DeleteField_management(fc, f.name)
JohnPapageorgiou
New Contributor III

Thank you Josh!  That did the trick.

0 Kudos