How to delete fields based off of another layer's fields?

1652
4
04-28-2016 07:57 AM
KellyZiegenfuss2
New Contributor

Hi All,

I am trying to compare the fields of two layers and delete any that are different. This is the code that I thought would work, but it returns RuntimeError: Object: Error in executing tool. Any ideas?

import arcpy

List = arcpy.ListFields("Layer 1")
x = arcpy.ListFields("Layer 2")

for i in x:
    if i in List:
        print i
    else:
        arcpy.DeleteField_management("Layer 2", I)

0 Kudos
4 Replies
MitchHolley1
MVP Regular Contributor

Kelly,

Have you tried running it?  If so, did you get any errors?

0 Kudos
DanPatterson_Retired
MVP Emeritus

Delete Field—Help | ArcGIS for Desktop

From there, there is some things you should add to your script, like the workspace.  it might be a wise idea to check that you are deleting from a table view and that the table isn't open in the project.  Also, you are running this from within a project too, since it won't work as a standalone script.  So any information that can elaborate on the conditions that you are running this script under might be useful.

0 Kudos
NeilAyres
MVP Alum

As Dan says, first include the env.workspace to change to this workspace.

Then ListFields returns a fields object, which has various properties (or attributes).

so :

fldsFirst = [f.name for f in arcpy.ListFields(fc)]

will give you a list of the field names.

Do this on both then run your other loop to delete the fields in the second fc.

Back up your original fc's first, you never know when your routine might do something you may not have intended.

All this assuming you are running this in an IDE, not a python window inside ArcMap or wherever.

0 Kudos
EarlSarow
New Contributor III

A couple of things:

First, In your code snippet, it looks like your using lower case "i" for the field variable in your loop, but you're using an upper case "I" on the DeleteField_management command. 

Second, the DeleteField_management command wants a list of field names to delete, not a single field.  It would be more efficient for you to first construct a list of field names to delete, then delete them all with a single call to DeleteField_management. 

Take a look at the examples here:  DeleteField_management​

Example 3 shows how to programatically build lists of fields then delete them.