I'm exporting my feature class to a CSV file. I figured how to keep the fields I need on export.
Is there a way to keep the alias field name on export?
I'm also open to writing out the correct headers but can't figure out how.
#Export out as CSV
out_folder_path = arcpy.GetParameterAsText(0)
outputCSV = os.path.join(out_folder_path, "Points" + ".csv")
fields = arcpy.ListFields(fc)
fieldsToKeep =['REPORTER','RECOWNER','SCINAME','COMNAME','RECBASIS','GlobalID','OCCSTATUS','MANAGESTAT',
'POPSTAT','OBSDATE','COUNTRY','STATE','COUNTY','PRIVATE','LATITUDE','LONGITUDE',
'ABUNDANCE','INFESTAREA','INFESTUNIT','PCTCOVER','VISITTYPE','COMMENTS']
field_names = [field.name for field in fields if field.name in fieldsToKeep]
with open(outputCSV,'w', newline='') as f:
w = csv.writer(f)
w.writerow(field_names)
for row in arcpy.SearchCursor(fc):
field_vals = [row.getValue(field.name) for field in fields if field.name in fieldsToKeep]
w.writerow(field_vals)
del row
1 Answer 1
The documentation for the 'field' class explains that the .aliasName
attribute holds the value of the field alias. So change the field_names =
line to this:
field_names = [field.aliasName for field in fields if field.name in fieldsToKeep]
Or if you want to be a bit clearer, change it to this:
field_aliases = [field.aliasName for field in fields if field.name in fieldsToKeep]
...
...
...
w.writerow(field_aliases)