Export Attribute Table to .csv

12807
4
10-23-2015 07:43 AM
mpboyle
Occasional Contributor III

I'm looking to export an attribute table to a .csv file using the csv module within python.  I'm wondering what is the best way to do this with multiple fields...?  Do you use a search cursor to iterate over the rows?  How can you include field names...?

I realize I could use the Table to Excel function or the Table to ASCII, but I believe for large datasets this would be faster and create a smaller output.

Tags (1)
0 Kudos
4 Replies
BruceHarold
Esri Regular Contributor

Hi

There are a couple of tools available in the gallery:

http://www.arcgis.com/home/search.html?q=CSV&t=content&focus=tools

Regards

mpboyle
Occasional Contributor III

Bruce Harold​,

Those tools are definitely nice to know about!

As I'm far from a python expert, below is what I have and seems to work...without any domain translating...

import arcpy
import csv

fc = r'...path to input fc...'
fields = ['field1', 'field2', 'field3']
outCsv = r'...path to output csv...'

with open(outCsv, 'wb') as ouputCsv:
    writer = csv.writer(outputCsv)
    writer.writerow(fields)  # writes header containing list of fields
    rows = arcpy.da.SearchCursor(fc, field_names=fields)
    for row in rows:
        writer.writerow(row)  # writes fc contents to output csv
    del rows
JamesCrandall
MVP Frequent Contributor

I typically use pandas DataFrame.to_csv for this operation as I mostly work with that library.  But NumPy also has similar method that you could just convert your feature class or table to a NumPy array and save it out from there.

import numpy
import arcpy

lyr = r'H:\Documents\ArcGIS\Default.gdb\MyFeatureClass'
nparr = arcpy.da.FeatureClassToNumPyArray(lyr, ['OBJECTID','STNAME','CNTYFIPS','Shape_Area'])
numpy.savetxt('H:\MyFeatureClass.csv', nparr, delimiter=",", fmt="%s")
BlakeTerhune
MVP Regular Contributor

Here's what I use for exporting to CSV.

import arcpy
import csv
import os

# Environment variables
workingDir = r"C:\temp"
workingGDB = os.path.join(workingDir, "MyGeodatabase.gdb")
inputTable = os.path.join(workingGDB, "MyInputTable")
outputCSV = os.path.join(workingDir, "MyOutput.csv")

# Create CSV
with open(outputCSV, "w") as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=',', lineterminator='\n')
    ## Write field name header line
    fields = ['FirstField','NextField','AndThirdExample']
    csvwriter.writerow(fields)
    ## Write data rows
    with arcpy.da.SearchCursor(inputTable, fields) as s_cursor:
        for row in s_cursor:
            csvwriter.writerow(row)