问题
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:
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,,,,,,,,
来源:https://stackoverflow.com/questions/21022675/write-each-list-as-a-column-in-csv-table