How to write two lists of different lengths to columns and rows in a csv file
I have two lists of different lengths:
list1 = ['a']
list2 = [['apple','banana','grapes']]
The csv I want is the following:
col1 col2
a apple, banana, grapes
So first I tried itertool
and izip
, but it seems to only put the first element of the list in list2 of col2, so it looks like :
col1 col2
a apple
How to get the version above, with the full list in list2 as rows?
I used the following code to store the above to csv:
import csv
from itertools import izip
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(izip(list1,sum(list2,[]))
Solution
izip
truncates longer lists to match shorter lists, so izip(
[‘a’], [‘a’, ‘b’, ‘c’]) actually gives [‘a’, 'a']
, which is where the problem comes from.
Also, usually you will want to use str.join
() instead of sum()
to convert the list to a string.
Based on this question, I guess you want a CSV file delimited by tabs. To solve the problem, first convert list2
to a string list:
>>> list2_str = [','.join(lst) for lst in list2]
['apple,banana,grapes']
Then compress list1
and list2_str
:
>>> list3 = zip(list1, list2_str)
[['a', 'apple,banana,grapes']]
Open a csv writer in the “excel-tab” dialect and write the line:
>>> writer = csv.writer(file, dialect='excel-tab')
>>> writer.writerows(list3)
If you want a csv file delimited by “,”, just remove the dialect
parameter. Python will correctly reference the second column, generated
a,"apple,banana,grapes"
In a CSV file.