4

I have 2 lists let's say

a = [1,2,3] 
b = [4,5,6]

I want to write them in two columns in CSV file so when I open the excel sheet I see something like this :

col1              col2

1                  4

2                  5

3                  6

How can I do this?

I used zip(a,b) but the result is stored in one column:

col1 

1 4

2 5

3 6
Mazdak
  • 105,000
  • 18
  • 159
  • 188
Shideh Hm
  • 69
  • 1
  • 5

2 Answers2

3

You need to use csv.Dictwriter() to be able to specify the field names.

import csv

with open('numbers.csv', 'w', newline='') as csvfile:
    fieldnames = ['col1', 'col2']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i, j in zip(a, b):
        writer.writerow({'col1': i, 'col2': j})

Or instead of a regular for loop you could use writerows and a list comprehension:

writer.writerows([{'col1': i, 'col2': j} for i,j in zip(a,b)])
Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

Using pandas is very easy. Just:

import pandas as pd

and then:

In [13]: df = pd.DataFrame({'col1':a, 'col2':b})

In [14]: df
Out[14]: 
   col1  col2
0     1     4
1     2     5
2     3     6

In [15]: df.to_csv('numbers.csv', index=False)

Basically you are building a dataframe with your lists and then save back to .csv. Hope that helps.

Fabio Lamanna
  • 20,504
  • 24
  • 90
  • 122