user861938
user861938

Reputation: 83

Writing 2 lists to a csv as column names and subsequent values

I have 2 lists and I am trying to create a csv from them. I want to write the values of the 1st list as column names and the entries from 2nd list as the corresponding values for those columns. For e.g.:

1st list = ['A', 'B', 'C','D','E']
2nd list = [['1','2','3','4','5'], ['6','7','8','9','10']]

I want the csv to look like:

A     B     C     D     E
1     2     3     4     5
6     7     8     9     10

I tried writing the 1st list as a single row using csv writer.writerows and it successfully came as the column names. However, when I try to write the 2nd list to the same csv file, it overwrites the column names. I also tried to zip both the lists and then write them to the file but that also didn't help.

Could you please suggest me the way to approach this problem? I would appreciate the suggestions. Thanks!

Upvotes: 0

Views: 105

Answers (1)

G_M
G_M

Reputation: 3382

In[2]: one = ['A', 'B', 'C','D','E']
  ...: two = [['1','2','3','4','5'], ['6','7','8','9','10']]
In[3]: import csv
  ...: 
  ...: with open('outfile.csv', 'w') as f:
  ...:     writer = csv.writer(f)
  ...:     writer.writerow(one)
  ...:     writer.writerows(two)
  ...: 
In[4]: with open('outfile.csv', 'r') as f:
  ...:     print(f.read())
  ...: 
A,B,C,D,E
1,2,3,4,5
6,7,8,9,10

Upvotes: 1

Related Questions