如何在python中将两列导出到csv

时间:2018-04-04 02:39:52

标签: python csv

我不熟悉如何将列表导出到python中的csv。这是一个列表的代码:

import csv
X = ([1,2,3],[7,8,9])
Y = ([4,5,6],[3,4,5])
for x in range(0,2,1):
    csvfile = "C:/Temp/aaa.csv"
    with open(csvfile, "w") as output:
        writer = csv.writer(output, lineterminator='\n')
        for val in x[0]:
            writer.writerow([val])

我想要结果:

enter image description here

那么如何修改代码(主要问题是如何更改列?)

3 个答案:

答案 0 :(得分:1)

要输出多列,您可以使用zip(),如:

代码:

import csv

x0 = [1, 2, 3]
y0 = [4, 5, 6]
x2 = [7, 8, 9]
y2 = [3, 4, 5]
csvfile = "aaa.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    writer.writerow(['x=0', None, None, 'x=2'])
    writer.writerow(['x', 'y', None, 'x', 'y'])
    for val in zip(x0, y0, [None] * len(x0), x2, y2):
        writer.writerow(val)

结果:

x=0,,,x=2
x,y,,x,y
1,4,,7,3
2,5,,8,4
3,6,,9,5

答案 1 :(得分:0)

你可以尝试:

with open('file.csv') as fin:
    reader = csv.reader(fin)
    [fout.write(r[0],r[1]) for r in reader]

如果您需要进一步的帮助,请发表评论。

答案 2 :(得分:0)

处理csv文件时,你应该只使用Pandas。将标头和数据放入数据框中,然后在该数据框上使用.to_csv方法。当你的字符串包含逗号等时,Csv会变得棘手......

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html