Export an attribute table to .txt using arcpy.

13730
2
10-29-2013 02:22 PM
FredKellner1
New Contributor
This seems like a no-brainer, perhaps I'm missing something. I can easily export tables to .txt format using the the Arcmap interface, but can't do so using arcpy. I have tried the table to table conversion function but this supports every format but a simple .txt file. Is there a work around?

Fred
Tags (2)
0 Kudos
2 Replies
XanderBakker
Esri Esteemed Contributor
Hi Fred,

You're right that .TXT is not a supported output format in the Table to Table conversion tool. If you work with a featureclass instead of a table the "Export Feature Attribute to ASCII (Spatial Statistics)" would be an option.

If not than you can use the snippet below I found on stack exchange:
http://gis.stackexchange.com/questions/17933/export-table-to-x-y-z-ascii-file-via-arcpy


import arcpy,csv

table =r'c:\path\to\table'
outfile = r'c:\path\to\output\ascii\text\file'      

#--first lets make a list of all of the fields in the table
fields = arcpy.ListFields(table)
field_names = [field.name for field in fields]

with open(outfile,'wb') as f:
    w = csv.writer(f)
    #--write all field names to the output file
    w.writerow(field_names)

    #--now we make the search cursor that will iterate through the rows of the table
    for row in arcpy.SearchCursor(table):
        field_vals = [row.getValue(field.name) for field in fields]
        w.writerow(field_vals)
    del row


Please note that things may go wrong with binary (blob) fields and perhaps with Null values as well.

Kind regards,

Xander
0 Kudos
FredKellner1
New Contributor
Hi Xander,

Thanks for you input that snippet from GIS stack exchange was just what I needed!

Fred
0 Kudos