Home > database >  Writing data in two columns using CSV format in Python
Writing data in two columns using CSV format in Python

Time:03-08

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

CodePudding user response:

You can transpose rows an columns with the zip function:

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