在Python 3中编写csv文件

时间:2014-03-31 10:12:37

标签: python

我有三个列表abc,我想将这些列表写为csv文件。我遇到了麻烦(因为data将这些作为行)并且还编写了csv。这就是我所拥有的。

import csv

my_output=open('myfile.csv','wb')
mywriter=csv.writer(csv_out)

a=[1,3,5,7]
b=[2,4,6,8]
c=[0,0,0,0]
data=[a,b,c]

for item in data:
    mywriter.writerow(item)
my_output.close()

2 个答案:

答案 0 :(得分:0)

Excel将数据存储在Row-major order

你必须先解决问题:

a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]

for i in range(len(data[0])):
    for j in range(len(data)):
        print data[j][i],
    print ''

<强>输出:

1 2 0 
3 4 0 
5 6 0 
7 8 0 

全部放在一起:

import csv

my_output = open('myfile.csv', 'wb')
mywriter = csv.writer(my_output)

a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]

for i in range(len(data[0])):
    row = [data[j][i] for j in range(len(data))]
    mywriter.writerow(row)

my_output.close()

更短(更安全)的版本:

import csv

my_output = open('myfile.csv', 'wb')
mywriter = csv.writer(my_output)

a = [1,3,5,7]
b = [2,4,6,8]
c = [0,0,0,0]
data = [a,b,c]

for row in zip(*data):
    mywriter.writerow(row)

my_output.close()

有关此内置功能的信息,请参阅zip([iterable, ...])

答案 1 :(得分:0)

无需创建变量data。使用内置功能zip。它使迭代器聚合来自每个迭代的元素。

for item in zip(a, b, c):
    mywriter.writerow(item)

参考文档https://docs.python.org/3/library/functions.html#zip