4 Comments

Export Shapefile as .csv tutorial


I recently had issues with a simple export to .csv. What I wanted to do is pull in a shapefile and delete a bunch of fields and then export it out to a .csv (this works the same for saving to a text file). It actually turned out easier than I thought as I did not need to delete all the fields but rather I just wrote out the fields that I wanted to keep:


# Import system modules
import sys, string, os, glob, csv
import arcgisscripting
# Create the Geoprocessor object
gp = arcgisscripting.create()

# System arguments
input = sys.argv[1]
output = sys.argv[2]

# Set our new outputnew to be opened output with write privileges.
outputnew=open(output,'wb')

# Set linewriter as csv.writer written out to outputnew
# The delimiter can be set as comma, pipe etc.
linewriter=csv.writer(outputnew, delimiter=',')

# If you want to pass all fields thru then disregard this.  I use this as I only want to pass some of the fields out and these are listed in Python list
good_fields = ['field 1', 'field 2', 'field 3', 'field 4', 'field 5']

# Now we go thru all of the fields and keep just those that are in the list of good fields
flds=gp.ListFields(stops_in)
fld = flds.Next()
header=[]
while fld:
    if fld.Name in good_fields:
        value=fld.Name
        header.append(value)
    fld = flds.Next()
linewriter.writerow(header)

# And we run thru each row populating the kept fields
row=cursor.Next()
row_num = 1
while row:
    line=[]
    if row_is_valid(row_num, row):
        for fld in header:
            value=row.GetValue(fld)
            line.append(value)
        linewriter.writerow(line)
    row=cursor.Next()
    row_num += 1

del cursor
gp.AddMessage("Finished")
output.close()


I originally attempted to make a copy of the original shapefile and then a table view from the shapefile. In the end all I needed to do was simply read the input shapefile and then write it out to the .csv file.

4 comments on “Export Shapefile as .csv tutorial

  1. Could this be modified to export to dbf instead of csv?

  2. hi, where should I run this script?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: