2

I'm exporting a feature class as a CSV through Python with ArcGIS Pro. I've listed out all the fields I need to keep on export.

Is it possible to use this as a list for ordering my headers in the CSV?

There's a csv.DictWriter but I can't figure out where/how to combine it. I thought listing it out preserves the order in export but it does not.

fields = arcpy.ListFields(fc3)
fieldsToKeep =['REPORTER','RECOWNER','SCINAME','COMNAME','RECBASIS','GlobalID','OCCSTATUS','MANAGESTAT',
               'POPSTAT','OBSDATE','COUNTRY','STATE','COUNTY','COMMENTS']

field_names = [field.aliasName for field in fields if field.name in fieldsToKeep]

with open(outputCSV,'w', newline='') as f:
    w = csv.writer(f)
    #w = csv.DictWriter(f, field_names)
    w.writerow(field_names)
    for row in arcpy.SearchCursor(fc3):
        field_vals = [row.getValue(field.name) for field in fields if field.name in fieldsToKeep]
        w.writerow(field_vals)
        del row 
0

1 Answer 1

2

You just need to make sure to read the values from each row in the desired order. Try this:

fields = arcpy.ListFields(fc3)
aliases = {field.name: field.aliasName for field in fields}

fieldsToKeep =['REPORTER','RECOWNER','SCINAME','COMNAME','RECBASIS','GlobalID','OCCSTATUS','MANAGESTAT',
               'POPSTAT','OBSDATE','COUNTRY','STATE','COUNTY','COMMENTS']

aliasesToKeep = [aliases[name] for name in fieldsToKeep]

with open(outputCSV,'w', newline='') as f:
    w = csv.writer(f)
    w.writerow(aliasesToKeep)
    with arcpy.da.SearchCursor(fieldsToKeep) as cursor:
      for row in cursor:
          w.writerow(row)

Notes:

  • Always use the arcpy.da / "data access" cursors. The old-style ones are deprecated
  • Using with to create a context for the cursor removes the need to del anything
  • The cursor will now return a tuple of values for each row, in the same order as the fields we've requested

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.