Select to view content in your preferred language

Using fieldmappings with arcpy.FeatureClasstoFeatureClass_conversion method

1436
2
Jump to solution
08-06-2012 07:43 AM
MarcCusumano
Regular Contributor
I'm trying to copy feature from one feature class to another with only certain fields and an SQL query. I can't seem to get the field mappings object to work right. Here is what I have:

import arcpy from arcpy import env  arcpy.env.overwriteOutput = True  in_path =r"Database Connections/Sun120 - 5151.sde/CONVERSION." in_feature = "CPTESTPOINTINSPECTION" out_path = r"E:/Rich Anderson/CP_ReChecks/" FileGDBName = "Test.gdb" infc1 = in_path + in_feature  try:       fieldmappings = arcpy.FieldMappings()          fieldmappings.addTable(infc1)      fldmap_READING = arcpy.FieldMap()      fldmap_READING.addInputField(infc1, "READING")     fld_READING = fldmap_READING.outputField     fld_READING.name = "READING"     fldmap_READING.outputField = fld_READING     fieldmappings.addFieldMap(fldmap_READING)                            arcpy.FeatureClassToFeatureClass_conversion(in_path + in_feature, out_path + FileGDBName, "Max_CP_Inspection_Date_Test", " \"READING\" > 85 ", fieldmappings)  except Exception as e:     print e


This works but just adds a new field called "READING_1" with all null values to the output feature class along with all of the other fields (including the original "READING" field and its values).

How can I get the feature class to feature class tool to only copy the fields I want? I've been at this for over four hours! Thanks...
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
KimOllivier
Honored Contributor
It has taken me years to work out how to use fieldmapping(s) objects, so 4 hours is just a start.

Here is a snippet of code to help. What I am doing is merging a library of coverage tiles (remember them? still useful)
My most reliable way to get it to work is to create a fieldmappings object from the source and then delete fields that
I don't want from a list. You could reverse the logic and delete all fields except the ones you do want.
Note that when I merge I have to add each input source fieldmap, just having the output names once will not do!

The alternative is to use the CopyFeatures tool interactively and copy the result as a python snippet for a static version.
It produces a string equivalent of a fieldmap which is not ideal, and really hard to edit. I do this when scripting fails and I have to run the tool interactively. I just get out last month's result, open it as a dialog and rerun.

    start = datetime.datetime.now() droplst = ["xxx","rings_ok","rings_nok","lpoly#","rpoly#", "fnode#","tnode#","length","area","perimeter",  "multi","case1","case2","case3", "$SCALE","$ANGLE","PAR-ID","OTHR#","OTHR-ID",]  sr = arcpy.SpatialReference() sr.factoryCode = 2193 # NZTM sr.create() arcpy.env.outputCoordinateSystem = sr   ws = "e:/lib/nztm/tile"   arcpy.env.workspace = ws+"/t1001/data"  dictCov = {    "add_all":"address/point",                      "emf":"emf/point",                "fename":"fename/point",                "hydro":"hydro/polygon",                 "titledif":"titledif/point",                "up":"up/point",                "uparcel":"uparcel/point"            } l # lstFC = ["uparcel"]  for outFCName in lstFC :     cov = dictCov[outFCName]     fds = cov.split("/")[0]     print "Processing",outFCName,cov     arcpy.AddMessage(outFCName)      if not arcpy.Exists(gdb+"/"+outFCName) :             lstSrc = []             for ld in range(12) :                 tile = "t%d" % (ld + 1001)                 srcCov = ws+"/"+tile+"/data/"+cov                 if arcpy.Exists(srcCov) :                     lstSrc.append(srcCov)                 else :                     arcpy.AddError(srcCov+'not found')                     print srcCov,"NOT FOUND"             # Create FieldMappings object to manage merge output fields             fieldMappings = arcpy.CreateObject("FieldMappings")             # Add all fields from sources             for src in lstSrc:                 fieldMappings.addTable(src)             # hide fields             print "    removing ",             for fld in [fds+"#",fds+"-ID"] + droplst: #include cov# and cov-id                 pos = fieldMappings.findFieldMapIndex(fld.upper())                 # print pos,fld                 if pos >= 0 :                     fieldMappings.removeFieldMap(pos)                     print fld.upper(),             print             print "    keeping  ",             for x in range(fieldMappings.fieldCount):                 print fieldMappings.getFieldMap(x).outputField.name,             print             arcpy.Merge_management(lstSrc, gdb+"/"+outFCName,fieldMappings )             print outFCName,"merged"             arcpy.AddMessage(outFCName+" merged")     else :             print "Skipping load of",outFCName             arcpy.AddWarning("Skipping load of "+outFCName)

View solution in original post

0 Kudos
2 Replies
KimOllivier
Honored Contributor
It has taken me years to work out how to use fieldmapping(s) objects, so 4 hours is just a start.

Here is a snippet of code to help. What I am doing is merging a library of coverage tiles (remember them? still useful)
My most reliable way to get it to work is to create a fieldmappings object from the source and then delete fields that
I don't want from a list. You could reverse the logic and delete all fields except the ones you do want.
Note that when I merge I have to add each input source fieldmap, just having the output names once will not do!

The alternative is to use the CopyFeatures tool interactively and copy the result as a python snippet for a static version.
It produces a string equivalent of a fieldmap which is not ideal, and really hard to edit. I do this when scripting fails and I have to run the tool interactively. I just get out last month's result, open it as a dialog and rerun.

    start = datetime.datetime.now() droplst = ["xxx","rings_ok","rings_nok","lpoly#","rpoly#", "fnode#","tnode#","length","area","perimeter",  "multi","case1","case2","case3", "$SCALE","$ANGLE","PAR-ID","OTHR#","OTHR-ID",]  sr = arcpy.SpatialReference() sr.factoryCode = 2193 # NZTM sr.create() arcpy.env.outputCoordinateSystem = sr   ws = "e:/lib/nztm/tile"   arcpy.env.workspace = ws+"/t1001/data"  dictCov = {    "add_all":"address/point",                      "emf":"emf/point",                "fename":"fename/point",                "hydro":"hydro/polygon",                 "titledif":"titledif/point",                "up":"up/point",                "uparcel":"uparcel/point"            } l # lstFC = ["uparcel"]  for outFCName in lstFC :     cov = dictCov[outFCName]     fds = cov.split("/")[0]     print "Processing",outFCName,cov     arcpy.AddMessage(outFCName)      if not arcpy.Exists(gdb+"/"+outFCName) :             lstSrc = []             for ld in range(12) :                 tile = "t%d" % (ld + 1001)                 srcCov = ws+"/"+tile+"/data/"+cov                 if arcpy.Exists(srcCov) :                     lstSrc.append(srcCov)                 else :                     arcpy.AddError(srcCov+'not found')                     print srcCov,"NOT FOUND"             # Create FieldMappings object to manage merge output fields             fieldMappings = arcpy.CreateObject("FieldMappings")             # Add all fields from sources             for src in lstSrc:                 fieldMappings.addTable(src)             # hide fields             print "    removing ",             for fld in [fds+"#",fds+"-ID"] + droplst: #include cov# and cov-id                 pos = fieldMappings.findFieldMapIndex(fld.upper())                 # print pos,fld                 if pos >= 0 :                     fieldMappings.removeFieldMap(pos)                     print fld.upper(),             print             print "    keeping  ",             for x in range(fieldMappings.fieldCount):                 print fieldMappings.getFieldMap(x).outputField.name,             print             arcpy.Merge_management(lstSrc, gdb+"/"+outFCName,fieldMappings )             print outFCName,"merged"             arcpy.AddMessage(outFCName+" merged")     else :             print "Skipping load of",outFCName             arcpy.AddWarning("Skipping load of "+outFCName)
0 Kudos
MarcCusumano
Regular Contributor
This actually proved so time-consuming I just did a complete workaround by having the table created in a separate SQL statement that is executed from the command line. Much simpler. Thanks for the assistance though, Kim.
0 Kudos