[GIS] Feature class to Feature class not working

arcgis-10.0arcgis-desktoparcpy

I am trying to use the Featureclass to Featureclass conversion tool to make a copy of an existing layer (in a geodatabase). My primary motive is to copy over only a few (2 out of 18) fields to the new feature class. I have put a simple script to do this, but this copies all the fields even tough I specify the field names that should be copied.

Can someone please let me know what am i doing wrong.

I want the output feature class (Test) to have two fields A and B.

# Import arcpy module
import arcpy


# Local variables:
Input = "C:\\Work\\Projects\\0a_IL_Naperville\\Segmenter_v8\\1 00001 IL Naperville 2013.gdb\\Streets"
Out_location = "C:\\Work\\Projects\\0a_IL_Naperville\\Segmenter_v8\\1 00001 IL Naperville 2013.gdb"

keep = ['ST_NAME','FUNC_CLASS','Shape_Length','OBJECTID','Shape','A']

arcpy.FeatureClassToFeatureClass_conversion(Input,Out_location, "Test",field_mapping=keep)

Best Answer

If you look at ESRI'S field map documentation, it seems the good way to specify fields is with a arcpy.FieldMap() object. The second example on the documentation seems to fit your needs :

import arcpy

# Set the workspace
arcpy.env.workspace = 'c:/base/data.gdb'

in_file = 'AccidentData'
out_file = 'AverageAccidents'

# Create the necessary FieldMap and FieldMappings objects
fm = arcpy.FieldMap()
fm1 = arcpy.FieldMap()
fms = arcpy.FieldMappings()

# Each field with accident data begins with 'Yr' (from Yr2007 to Yr2012).
# The next step loops through each of the fields beginning with 'Yr',
# and adds them to the FieldMap Object
for field in arcpy.ListFields(in_file, 'Yr*'):
    fm.addInputField(in_file, field.name)

# Set the merge rule to find the mean value of all fields in the
# FieldMap object
fm.mergeRule = 'Mean'

# Set properties of the output name.
f_name = fm.outputField
f_name.name = 'AvgAccidents'
f_name.aliasName = 'AvgAccidents'
fm.outputField = f_name

# Add the intersection field to the second FieldMap object
fm1.addInputField(in_file, "Intersection")

# Add both FieldMaps to the FieldMappings Object
fms.addFieldMap(fm)
fms.addFieldMap(fm1)

# Create the output feature class, using the FieldMappings object
arcpy.FeatureClassToFeatureClass_conversion(
    in_file, arcpy.env.workspace, out_file, field_mapping=fms)
Related Question