[GIS] Copying feature class and retaining selected fields using ArcPy

arcpyfield-mapping

I've got a featureclass (fc) that I want to copy, but only retaining a selected number of fields, let's say field 9, 11, and 12 from the total of 15 fields. I want to use arcpy and suspect that fieldmappings are somehow required for this. I currently have:

fm= arcpy.FieldMappings()
fm.addtable(fc)
sel= range(0,9)+[10]+range(13,16)
for i in sel:
    fm.removeFieldMap(i)

However, this gives:

RuntimeError: FieldMappings: Error in removing a field map from field mappings for RemoveFieldMap

I can't quite see what I'm doing wrong? Perhaps it would be nicer to somehow select the fields I want and add these to a new fieldMapping object? All suggestions are welcome, thanks in advance!

Update. As suggested below, I now have the following:

inFields= ["fA", "fB", "fC"]
inTab= 'testFc'
fm= arcpy.fieldMappings()
fieldMap= arcpy.FieldMap()
for field in inFields: 
    fieldMap.addInputField(inTab, field)
fm.addFieldMap(fieldMap)
arcpy.featureClassToFeatureClass_conversion(testFc, outDir, testOutFc, field_mapping= fm)

This works, a new featureclass is created. However, it contains only field fA. The python output reads:

Executing: FeatureClassToFeatureClass L:/GEOProjects/2Working.gdb/testFc :/GEOProjecten outDir testOutFc
# "fA "fA" true true false 8 Double 0 0 ,First,#,
L:/GEOProjects/2Working.gdb/testFc,fA,-1,-1,
L:/GEOProjects/2Working.gdb/testFc,fB,-1,-1,
L:/GEOProjects/2Working.gdb/testFc,fC,-1,-1" #
Start Time: Thu Oct 24 10:21:42 2013
Succeeded at Thu Oct 24 10:21:58 2013 (Elapsed Time: 16.00 seconds)

It seems that ony fA is being copied to the new featureclass.

Any suggestion as to why this can be?

Best Answer

Note: I've edited this answer to correct a mistake highlighted above

The problem is you are removing the field map to the table, and not removing the fields from the field map. So, it removes the first (and only) fieldmap, then it doesn't know what to do when you tell it to look for the next fieldmap.

What you need to do is create a new fieldmap and add the fields you want into it. Then, add it to your fm object. It would go something like this:

inTab = "InputTableName"
inFields = ['List','Of''Field','Names'] #case-sensitive

fm = arcpy.FieldMappings()
fieldMap = arcpy.FieldMap()
for field in fieldList:

   #creates a fieldmap with name of input field
   vars()[field] = arcpy.FieldMap()

   fieldMappings.addFieldMap(vars()[field])
   fm.AddFieldMap(vars()[field])

Bear in mind, that code may need some adjusting, but it should get you in the right direction.

Related Question