Select to view content in your preferred language

Add header to csv file

6580
11
11-22-2016 11:44 AM
jaykapalczynski
Honored Contributor

I am creating a csv file via the SearchCursor.  This Works great....although I am not getting the field names in there.  I went about this 2 ways.  I have tried a ton of forums but just cant seem to get the right syntax to create this ONLY once and when I bring it into Excel it has a header for each field.

Any thoughts?

I add the headers IN the "for row in cursor"

This adds them BUT it creates a set of headers for each record imported

with arcpy.da.SearchCursor(fc, [var_region_1 ,var_county_1,var_ramp_1], where_clause=expression) as cursor:
   for row in cursor:
       zval = str('{0},{1},{2}'.format(row[0],row[1],row[2]))
       headers = ['region_1','county_1','ramp_1']
       outFile.write('\t'.join(headers) + '\n')        
       outFile.write(zval + "%s\n")

‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

Add headers BEFORE the "for row in cursor"

This adds them but when I bring into excel they are all crammed into the first box, not spread out for each field.

headers = ['region_1','county_1','ramp_1']
outFile.write('\t'.join(headers) + '\n')

with arcpy.da.SearchCursor(fc, [var_region_1 ,var_county_1,var_ramp_1], where_clause=expression) as cursor:
   for row in cursor:
      zval = str('{0},{1},{2}'.format(row[0],row[1],row[2]))
      outFile.write(zval + "%s\n")

‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos
11 Replies
jaykapalczynski
Honored Contributor

Excel 2010...

Yea something weird is going on...If I copy the created .csv file from my server to my PC, then go File>open (not drag and drop it woks fine).  Drag and drop it carries to the next line.  But that only works once....then it gets all screwed up again...Very puzzled...going to try and decrease the characters being used in the header to see if that helps.

0 Kudos
jaykapalczynski
Honored Contributor

I stripped down a bunch of characters from the Header...it appears to be working now...definitely think I was hitting some sort of Character limit...I thank you very much for you help...spent way to long on this already...seems to be working...just watch how many characters I have from now on....

0 Kudos