0

I have multiple lists with each list containing strings that I want to fill in a csv table. I want each list to be a separate column of data in its respective column header. The header row is the same sequence as the outrow variable. With the code below it simply just fills in the first column with all the data from all the lists.

#outrow = (Layer,RasterCatalog,ShapeFile,Text,Terrain,GroupLayer,Locator,MapDocument,Toolbox,DbaseTable,RasterDataset)

#formats = (['Layer','RasterCatalog','ShapeFile','Text','Terrain','GroupLayer','Locator','MapDocument','Toolbox','DbaseTable','RasterDataset'])

# if I were to print(outrow), it would look like this:
   #(['H:\\Test\\Test_Data\\New Layer.lyr'], [], ['H:\\Test\\Test_Data\\New_Shapefile.dbf', 'H:\\Test\\Test_Data\\New_Shapefile.shp'], [], [], [], [], [], [], ['H:\\Test\\Test_Data\\New_dBASE_Table.dbf'], [])

def WriteCSVFile(csvFile,formats,outrow):

    ofile  = open(csvFile, "wb")        
    writer = csv.writer(ofile, delimiter=',')
    writer.writerow(formats) #making header here
    writer.writerows(outrow)
    ofile.close()

1 Answer 1

2

If I understand you correctly, then outrow is a list of lists, where each list contains one column, right? Then (assuming that they are all of the same length) you can simply zip() them together:

writer.writerows(zip(*outrow))

To illustrate:

>>> outrow = [[1,2,3], [4,5,6], [7,8,9]]
>>> import csv
>>> import sys
>>> w = csv.writer(sys.stdout)
>>> w.writerows(zip(*outrow))
1,4,7
2,5,8
3,6,9

If the columns are of different length, use izip_longest() from the itertools module (zip_longest() if you're on Python 3):

>>> import itertools
>>> outrow = (['H:\\Test\\Test_Data\\New Layer.lyr'], [], ['H:\\Test\\Test_Data\\New_Shapefile.dbf', 'H:\\Test\\Test_Data\\New_Shapefile.shp'], [], [], [], [], [], [], ['H:\\Test\\Test_Data\\New_dBASE_Table.dbf'], [])
>>> w.writerows(itertools.izip_longest(*outrow, fillvalue=""))
H:\Test\Test_Data\New Layer.lyr,,H:\Test\Test_Data\New_Shapefile.dbf,,,,,,,H:\Test\Test_Data\New_dBASE_Table.dbf,,,H:\Test\Test_Data\New_Shapefile.shp,,,,,,,,
Sign up to request clarification or add additional context in comments.

3 Comments

each list is different lengths
@wannabe_n00b: OK, and what should be put into the column after the list is empty? Perhaps you could show some example input and desired output. I may not have understood your question correctly.
Sure, I added some more info. I basically want each list to print vertically down the column.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.