1

I need to write a csv file that lists every record from an ID field across all feature classes in a gdb. The code I have written below does that fine, but I also need to write in the second column of the csv which feature class the record was found in.

I have been trying to create the cursor so that it also contains the fc name, then when I use writerow(row) both fields will be printed, but I think this is not a viable approach. Can anyone point me in the right direction? I'm using arcgis 10.2.2

arcpy.env.workspace = r'C:\Data.gdb'
output = r'C:\test.csv'

fcs = arcpy.ListFeatureClasses()
fieldnames = ['PropID', 'Feature Class']

with open(output, 'wb') as f:
    csvwriter = csv.writer(f)
    csvwriter.writerow(fieldnames)
    for fc in fcs:
         with arcpy.da.SearchCursor(fc,'PropID','PropID IS NOT NULL') as cursor:
            for row in cursor:
                csvwriter.writerow(row)
    del row, cursor 
  • 1
    The csv library seems to be pure Python and any questions that relate to that may be better researched at Stack Overflow. However, if you eliminate that from your code snippet and replace your write statements with print then you should have a smaller code snippet that focuses on the point at which you are actually stuck which is how to write/print a feature class name alongside every row created from a cursor on that feature class. – PolyGeo Mar 23 '16 at 2:51
  • I realized as I was sending that it might be better in Stack Overflow but Midavalo helped me out anyway, thanks! – JS24 Mar 24 '16 at 17:29
3

The csv.writer writes lists to csv, so you need to put your row value and your feature class names into a list before writing to the csv.

arcpy.env.workspace = r'C:\Data.gdb'
output = r'C:\test.csv'

fcs = arcpy.ListFeatureClasses()
fieldnames = ['PropID', 'Feature Class']

with open(output, 'wb') as f:
    csvwriter = csv.writer(f)
    csvwriter.writerow(fieldnames)
    for fc in fcs:
         with arcpy.da.SearchCursor(fc,'PropID','PropID IS NOT NULL') as cursor:
            for row in cursor:
                outtext = [row[0],fc]
                csvwriter.writerow(outtext)

    del row, cursor 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.