Here’s a little function for exporting an attribute table from ArcGIS to a CSV file. The function takes two arguments, these are a file-path to the input feature class or table and a file-path for the output CSV file (see example down further).
First import the necessary modules.
import arcpy, csv
Inside the function we use ArcPy to get a list of the field names.
def tableToCSV(input_tbl, csv_filepath): fld_list = arcpy.ListFields(input_tbl) fld_names = [fld.name for fld in fld_list]
We then open a CSV file to write the data to.
with open(csv_filepath, 'wb') as csv_file: writer = csv.writer(csv_file)
The first row of the output CSV file contains the header which is the list of field names.
writer.writerow(fld_names)
We then use the ArcPy SearchCursor to access the attributes in the table for each row and write each row to the output CSV file.
with arcpy.da.SearchCursor(input_tbl, fld_names) as cursor: for row in cursor: writer.writerow(row)
And close the CSV file.
csv_file.close()
Full script example…
import arcpy, csv def tableToCSV(input_tbl, csv_filepath): fld_list = arcpy.ListFields(input_tbl) fld_names = [fld.name for fld in fld_list] with open(csv_filepath, 'wb') as csv_file: writer = csv.writer(csv_file) writer.writerow(fld_names) with arcpy.da.SearchCursor(input_tbl, fld_names) as cursor: for row in cursor: writer.writerow(row) print csv_filepath + " CREATED" csv_file.close() fc = r"C:\Users\******\Documents\ArcGIS\Default.gdb\my_fc" out_csv = r"C:\Users\******\Documents\output_file.csv" tableToCSV(fc, out_csv)
Feel free to ask questions, comment, or help build upon this example.