Joshua Schappel
Joshua Schappel

Reputation: 49

Python Writing Rows and Cols to Excel

I am trying to write data into excel where every list is in a different column. So far I have been able to put the data into different columns in a csv file but when I open it in excel it writes all the data to the same column. What I have so far:

import csv

list1 = [1,2,3,4,5,6]
list2 = ['a','b','c','d','e','f']
list3 = ['G','H','I','J','K','L']


b = open('lists.csv','a')
a = csv.writer(b)

rows = zip(list1,list2,list3)


for row in rows:
    print(row)
    a.writerow([row])

b.close()

Current outcome:current outcome

Expected outcome: expected outcome

Upvotes: 1

Views: 2310

Answers (1)

skrx
skrx

Reputation: 20438

row is already a tuple so you don't have to put it into a list and can just write a.writerow(row).

Two more tips: Open the file with the with statement, then the file will be closed automatically.

When you open the file, pass newline='' to avoid the blank lines.

import csv

list1 = [1,2,3,4,5,6]
list2 = ['a','b','c','d','e','f']
list3 = ['G','H','I','J','K','L']

with open('lists.csv', 'a', newline='') as csv_file:
    writer = csv.writer(csv_file)
    for row in zip(list1, list2, list3):
        writer.writerow(row)

Upvotes: 1

Related Questions