user17471333
user17471333

Reputation:

Writing data in two columns using CSV format in Python

Using CSV format, I want to write the data in two columns. The current and the desired output are attached.

import csv  
A=[1,2,3]
B=[4,5,6]
header = ['1', '2']
data = [str(A), str(B)]

with open('Test.csv', 'w', encoding='UTF8') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write the data
    writer.writerow(data)

Current output:

enter image description here

Desired output:

enter image description here

Upvotes: 1

Views: 321

Answers (1)

blhsing
blhsing

Reputation: 106658

You can transpose rows an columns with the zip function:

writer = csv.writer(f)
writer.writerow(header)
writer.writerows(zip(A, B))

Upvotes: 2

Related Questions