9

I am very new to Python programming and have been tasked with writing a program to export a csv file from a file geodatabase feature class. The csv should contain only certain fields and the records exported should be based on last edit date. In other words the csv file will be created on a daily bases containing only the last features added based on "last edit date field".

I have this so far:

import arcpy
import os
import csv
import domainvalues

def export_to_csv(dataset, output, dialect):
    """Output the data to a CSV file"""
    # create the output writer
    out_writer = csv.writer(open(output, 'wb'), dialect=dialect)
    # return the list of field names and field values
    header, rows = domainvalues.header_and_iterator(dataset)

    # write the field names and values to the csv file
    out_writer.writerow(map(domainvalues._encodeHeader, header))
    for row in rows:
        out_writer.writerow(map(domainvalues._encode, row))

if __name__ == "__main__":
    # Get parameters
    dataset_name = arcpy.GetParameterAsText(0)
    output_file = arcpy.GetParameterAsText(1)
    delim = arcpy.GetParameterAsText(2).lower()
    dialect = 'excel'
    if delim == 'comma':
        pass
    else:
        dialect = 'excel-tab'
    try:
        export_to_csv(dataset_name, output_file, dialect)
    except Exception as err:
        arcpy.AddError('Error: {0}'.format(err))

However its exporting everything.

2
  • How do you post what you have so far? New to stackexchange also
    – user35267
    Jul 31, 2014 at 14:07
  • 2
    I think what Curlew means is that you should put some code in your question (edit your question) so it shows that you have tried to do this and then we can help you figure out where you may be going wrong (so it doesn't appear that you are just attempting to get the community to write a script for you). Jul 31, 2014 at 14:16

4 Answers 4

11

A simpler solution would be to convert to dbf file format, in which case you you can use the out-of-the-box Table to Table (Conversion). This tool also allows you the freedom to select which fields to include as FieldMappings as well as directly outputting a .dbf file.

import arcpy

fc = r'C:\path\to\your\fc'
outws = r'C:\temp'

arcpy.TableToTable_conversion (fc, outws, 'outFile.dbf')
2
  • 6
    -1 This creates a dbf file called outFile.dbf, not a csv file. Csv file output is not supported. Per the docs referenced: This tool can convert input tables to dBASE (.dbf), geodatabase (personal, file, or SDE), or INFO tables Jul 18, 2015 at 0:26
  • @ReganSarwas Thanks for the heads-up. I have edited the question to address your comments. The main idea here is that this is an alternative, simpler solution than converting to csv.
    – Aaron
    Jul 18, 2015 at 2:58
9

ArcGIS already has a tool to do this called "Export Feature Attributes to ASCII" which is in the Spatial Statistics--> Utilities toolbox.

The advantage of this tool over "Table to Table" is that you can 1) define your delimiter (space, comma, tab), 2) choose the fields you want to export and 3) choose whether or not to export your field names to the CSV file. It also happens to be a Python script, so you could copy that file and make your own variant of it very easily.

So, if you want to create a model or script to export only the most recent features based on "last edit date field", simply precede the "Export Feature Attributes to ASCII" tool with a "Select Layer by Attribute" tool where you call out the query you want to run.

2
  • 3
    While strictly answering the question as posted, it's worth noting that the tool only supports feature classes, not tables...
    – jburka
    Jun 24, 2016 at 13:11
  • I got Invalid field type error and I can't figure out why; fields defined as cols = [field.name for field in arcpy.ListFields(myshape)] and everything looks fine
    – a11
    Oct 16, 2020 at 3:34
4

Let's say you have a GDB file called treedn.gdb with a table called trees and you want to export to a CSV called trees.csv.

You can do something similar to this:

import arcpy
import csv

wd = #<working directory>
table   = wd+"/treedn.gdb/trees"
outfile = wd+"/treedn/trees.csv"      

fields = arcpy.ListFields(table)
field_names = [field.name for field in fields]

with open(outfile,'wb') as f:
    w = csv.writer(f)
    w.writerow(field_names)
    for row in arcpy.SearchCursor(table):
        field_vals = [row.getValue(field.name) for field in fields]
        w.writerow(field_vals)
    del row

the entire article is located here.

1

ArcGIS 10.3 has a new function ConvertTableToCsvFile_roads to convert a table into a CSV file. This is quite straightforward to use:

import arcpy
from arcpy import env

arcpy.env.workspace="C:/mydata.gdb"
arcpy.ConvertTableToCsvFile_roads("input_table", "C:myfolder/output_csv_file.csv", "COMMA")

See here the full doc.

Be aware you need a Roads and Highways toolbox license to use that. From version 10.4, this function is called ConvertTableToCsvFile_locref.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.