We have a script that regularly copies a bunch of feature classes out to shapefiles, keeping only the most important attributes (e.g. customer category) and dropping useless/private information (e.g. customer name).
Right now, it repeats the same set of steps without much variation. I am attempting to significantly simplify it by defining a function to do all those steps (the entire purpose of functions, of course.) Also, by introducing the arcpy.FieldMappings objects instead of verbose field mapping strings, it's possible to quickly understand what fields are coming from which data sources.
This works great for most of my feature classes.
def generate_field_mapping(inTable, inFieldList):
fm = arcpy.FieldMappings()
for field in inFieldList:
vars()[field] = arcpy.FieldMap()
vars()[field].addInputField(inTable, field)
fm.addFieldMap(vars()[field])
return fm
def subset_attributes(origFC, fieldList, outFC):
fStart = time.time()
name = origFC.split('.')[-1]
# make feature class with only desired fields
stringFieldMappings = generate_field_mapping(origFC, fieldList)
tempfc = os.path.join(scratchWS, "temp_{}".format(name))
arcpy.FeatureClassToFeatureClass_conversion(origFC, scratchWS, outFC, "", stringFieldMappings)
print " > done with {} ({} seconds)".format(name, round((time.time() - fStart), 2))
But, I have one feature class for which we want all of the fields dropped and I am not sure if I can accomplish this in the existing function workflow.
- If I pass an empty list of fields, it breaks:
FieldMap: Error in adding input field to field map
- If I pass an empty (
""
) value, and put in a conditional to skip fieldmapping if there's no list, then all the original fields are passed. - If I pass
OBJECTID
(logic being, that would definitely be in the output), it breaks:Field mapping error: merge rule not valid for output field OBJECTID
I'm happy to just bypass the fieldmapping part of the function with a conditional, but I am not sure how to drop all the resulting attributes. (I don't want to DeleteField_management each one, that would be clumsy and I switched to FieldMappings to get away from that.) Any ideas for a workaround?
scratchWS
is a geodatabase; input is from an SDE, output is to a local file gdb.