TransWikia.com

Adding input field to field map using ArcPy gives RuntimeError

Geographic Information Systems Asked on November 6, 2021

I’m a Python beginner and I would like to export a csv from a feature class, including only some fields. I’m trying to do it using the field mapping control, but I’m doing something wrong because I have the following error: RuntimeError: FieldMap: Error in adding input field to field map

here the code:

outPathTable = r"output_path"       #get parameter as text
myFc = r'myFc_path'                 #get parameter as text

outName = myFc + "_dataQualityFc.csv"

# List of fields to keep
outputFields = ['MemberID_target',
                         'PersonalID_target',
                         'Latitude', 
                         'Longitude', 
                         'dataQualityRisk_sameCH',
                          'dataQualityRisk_diffCH']

fieldMappings = arcpy.FieldMappings()

# Create the field mappings from the outputField list
# only fields in the list will be inlcuded in the exported file

for field in outputFields:
    fieldMap = arcpy.FieldMap()
    fieldMap.addInputField(myFc, field)
    fieldMappings.addFieldMap(fieldMap)
 

# Create a csv for Data Quality Risk using the field mapping 
arcpy.TableToTable_conversion(myFc, outPathTable, outName, "", fieldMappings)

One Answer

Here's how I did it:

  1. Set up the field mappings object
  2. Set up a nested Python dictionary with details on the fields I wanted
  3. Looped through that to add each individual field mapping
  4. Then the field mappings object could be used in the TableToTable_conversion

Kudos to this answer to Using Field Mapping with TableToTable_conversion in arcpy for leading me down the right path for loop in #3

fms = arcpy.FieldMappings()

fieldMappingDict = {
    1: {'fieldName':'ID','fieldType':'Text','fieldLength':8},
    2: {'fieldName':'Name','fieldType':'Text','fieldLength':128},
    3: {'fieldName':'Address1','fieldType':'Text','fieldLength':128},
    4: {'fieldName':'City','fieldType':'Text','fieldLength':64},
    5: {'fieldName':'Zip','fieldType':'Text','fieldLength':12},
    6: {'fieldName':'Phone','fieldType':'Text','fieldLength':18},
   ....
    }

#Loop through the mapping dictionary and set up individual field mappings to add to the fms
for cid, columnDef in fieldMappingDict.items():
    fm = arcpy.FieldMap()
    fm.addInputField(inTable,columnDef['fieldName'])
    newField = fm.outputField
    newField.type = columnDef['fieldType']
    newField.length = columnDef['fieldLength']
    fm.outputField = newField
    fms.addFieldMap(fm)

Answered by Mike D on November 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP