简体   繁体   English

在 Python 中使用 CSV 格式在两列中写入数据

[英]Writing data in two columns using CSV format in Python

Using CSV format, I want to write the data in two columns.使用 CSV 格式,我想将数据写入两列。 The current and the desired output are attached.当前和所需的 output 已附上。

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:当前output:

在此处输入图像描述

Desired output:所需的 output:

在此处输入图像描述

You can transpose rows an columns with the zip function:您可以使用zip function 调换行和列:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM