I have a script that writes a CSV based on fields from a feature class. Currently, the columns are defined by a field list, and a Search cursor loops through each item in the list to write to the CSV.
The list is defined by the positions of each field in the list. However, if the field order ever changes on the Feature Class, this list goes to pot.
How do I rewrite it so that I can define fld_list_final as a list of strings that match the actual field names, instead of their positions in the list?
So, for example, instead of the list being fn, fn etc, i want to be able to define it as 'TreeRef', 'Species', etc
# Create CSV of data for schedule if there are veteran trees import csv import os def tableToCSV(input_tbl, csv_filepath): fld_list = arcpy.ListFields(input_tbl) fn = [fld.name for fld in fld_list] fld_list_final = [fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn] with open(csv_filepath, 'w', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerow(fld_list_final) with arcpy.da.SearchCursor(input_tbl, fld_list_final) as cursor: for row in cursor: writer.writerow(row) csv_file.close() out_csv = csv_path+"\\"+(os.path.basename(fc_pnt))+".csv" tableToCSV(fc_pnt, out_csv) arcpy.AddMessage("CSV Generated.")
Solved! Go to Solution.