将列表写入CSV

时间:2017-03-15 20:25:07

标签: python list csv fwrite

我有一个列表,如:

[[A], [B], [A,B], [B], [C], [A, B, C], [C, A]]

我想把它写成CSV文件,如:

A,
B,
A,B,
B,
C,
A,B,C,
C,A,

请注意我有556,375个列表,每个列表至少包含20个变量。

3 个答案:

答案 0 :(得分:6)

要添加额外的逗号,只需在每行的末尾添加一个空单元格。

这是在writerows

中使用生成器理解的简短方法
import csv

l = [["A"], ["B"], ["A","B"], ["B"], ["C"], ["A", "B", "C"], ["C", "A"]]

with open("output.csv","w",newline="") as f:  # open("output.csv","wb") for Python 2
    cw = csv.writer(f)
    cw.writerows(r+[""] for r in l)

答案 1 :(得分:2)

file = open("myFile.csv", "w")
writer = csv.writer(file, delimiter = ",")
for list_ in myList:
     writer.writerow(list_)
file.close()

答案 2 :(得分:1)

您需要在行的末尾添加新行(\ n):

lista = [['A'], ['B'], ['A','B'], ['B'], ['C'], ['A','B','C'], ['C','A']]
f = open('lista.csv','a')
i = 0
while (i<len(lista)):   
    f.write(str(lista[i])+"\n")
    i = i + 1
f.close()