Write all rows in a feature class to a csv file

This is something I use often, although hardly ever in the same way twice.

#
# @date 16/04/2015
# @author Cindy Williams
#
# Writes the contents of a feature class to csv.
# Writing to csv is usually used when quickly
# needing to give file contents to a non-GIS
# person, or in creating a GIS inventory.
#
# For use as a standalone script.
#
import arcpy
import csv
arcpy.env.workspace = r"C:\Some\Arb\Folder"
csv_file = r"output.csv"
# Always create feature layer for faster access
ftr = arcpy.management.MakeFeatureLayer("work.gdb\ftr")
# Exclude all shape fields from output
fields = [field.name for field in arcpy.ListFields(ftr) if not field.name.startswith("Shape")]
with open(csv_file, 'wb') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
with arcpy.da.SearchCursor(ftr, fields) as cursor:
for row in cursor:
csvwriter.writerow(row)

I’ve included Line 21 because the main reason why you would be using this method in the first place, is because a non-GIS person has requested data from you. Usually, they don’t require any Shape information.

This way, you include only the attribute information. If they do require lengths/coordinates, it’s much easier to specify a Shape token such as SHAPE@LENGTH or SHAPE@XY than the field itself.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.