[GIS] Exporting shapefile to csv with cursor

arcpycsvcursor

I'm trying to export a shapefile to a csv file using a cursor. I found this quesion asked and answered here: Exporting table to XYZ ASCII file via ArcPy?

However I only want to export several specific columns in a specific order. I have been able to get the .csv header to export correctly but can't get the cursor to provide the data for the rows in that same order.

import arcpy
# import csv module
import csv

# Set working file location
dataBase = r"C:\Users\vince.adams\Desktop\VLA_FinalProject\GEARY"

# Set output file location
outFile = r"C:\Users\vince.adams\Desktop\VLA_FinalProject\Tables"
tableEight = outFile + "\Table8.csv"

# S_GEN_STRUCT
genStruct = dataBase + "\S_GEN_STRUCT.shp"
fieldList = ["WTR_NM", "STRUCT_NM", "STRUCT_TYP", "LOC_DESC", "STRUC_DESC"]

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

with open(tableEight,'wb') as outTable:
    writeOut = csv.writer(outTable)
    #--write all field names to the output file
    writeOut.writerow(fieldList)

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

    del row

I'm using Arc 10.2.

Best Answer

Since you're using ArcGIS 10.2, you can take advantage of the new SearchCursor in the Data Access module, which returns row values in the order of the fields specified. Try replacing your current cursor code with:

#--now we make the search cursor that will iterate through the rows of the table
for row in arcpy.da.SearchCursor(genStruct, fieldList):
    writeOut.writerow(row)
Related Question