export .dbf to .csv?

7234
4
01-31-2013 07:37 AM
by Anonymous User
Not applicable
Original User: Lynn_Carlson

Can someone help a python newbie with code to export .dbf to .csv?

arcpy.TableToTable_conversion seems to only work with .dbf and geodatabase. 

arcpy.CopyRows_management doesn't allow for .csv

I'm not finding any Export commands for tables.

Thank you!
0 Kudos
4 Replies
by Anonymous User
Not applicable
Original User: mzcoyle

I think you'd have to use a cursor and csv module to do this. I don't think there is a built in tool that exports to csv.

Here's a thread that is following a similar workflow.
http://gis.stackexchange.com/questions/42433/how-to-export-only-certain-columns-to-a-csv-file-in-arc...
0 Kudos
AndrewChapkowski
Esri Regular Contributor
Try using the python csv library and do something like this:
def get_rows(data_set, fields):
   with da.SearchCursor(data_set, fields) as cursor:
      for row in cursor:
         yield row
if __name__ == "__main__":
   data_set = arcpy.GetParameterAsText(0) # feature class/Table
   output = arcpy.GetParameterAsText(1) # csv file
   desc = arcpy.Describe(data_set)
   fieldnames = [f.name for f in desc.fields if f.type not in ["Geometry", "Raster", "Blob"]]
   rows = get_rows(data_set, fieldnames)
   with open(output,'wb') as out_file:
      out_writer = csv.writer(out_file)
      out_writer.writerow(fieldnames)
      for row in rows:
         out_writer.writerow(row)


Hope this gets you in the right direction.
0 Kudos
by Anonymous User
Not applicable
Original User: Caleb1987

Here's another way (also from stack exchange):

import arcpy
from os import path as p

def TableToCSV(fc,CSVFile):
    
    fields = [f.name for f in arcpy.ListFields(fc) if f.type <> 'Geometry']
    with open(CSVFile, 'w') as f:
        f.write(','.join(fields)+'\n') #csv headers
        with arcpy.da.SearchCursor(fc, fields) as cursor:
            for row in cursor:
                f.write(','.join([str(r) for r in row])+'\n')
    print 'Created %s Successfully' %p.basename(CSVFile)
0 Kudos
LynnCarlson__GISP
Occasional Contributor
Thank you - both options worked perfectly!
0 Kudos