Monday 10 July 2017

arcgis desktop - Exporting table to XYZ ASCII file via ArcPy?


I'm looking for a way to export an ArcGIS table (created with the Sample tool) to a text file via ArcPy.



I can do this in ArcGIS via the context menu by right-clicking the table, but have not found a way to script this.



Answer



You can do this using a cursor to grab the data from your table and write to a comma-delimited text file.


EDIT: I'm adding a more concise block of code to accomplish the task using the csv module of Python


New Answer using arcpy.da cursor:


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:
dw = csv.DictWriter(f,field_names)
#--write all field names to the output file
dw.writeheader()

#--now we make the search cursor that will iterate through the rows of the table

with arcpy.da.SearchCursor(table,field_names) as cursor:
for row in cursor:
dw.writerow(dict(zip(field_names,row)))

New Answer using old-style cursor:


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

Old answer:


import arcpy

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)

i = 1
f = open(outfile,'w')
for field in fields:
#--write all field names to the output file
if i < len(fields):

f.write('%s,' % field.name)
i += 1
else:
f.write('%s\n' % field.name)

#--now we make the search cursor that will iterate through the rows of the table
rows = arcpy.SearchCursor(table)
for row in rows:
i = 1
for field in fields:

if i < len(fields):
f.write('%s,' % row.getValue(field.name))
i += 1
else:
f.write('%s\n' % row.getValue(field.name))
del rows
f.close()

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...