将清单放入CSV

时间:2019-07-10 01:43:35

标签: python excel python-3.x

我在Python 3中有一个列表。我想将列表[1,2,3,4,5,6,7,8]分成一行[1,2,3,4]和[5] ,, 6,7,8]其他。我目前正在使用它来写入CSV,但是我正在手动进行拆分,并且在写入不确定如何摆脱它的信息后还会有一个空白单元格,这也是另一个问题

outfile = open('list.csv','w')
out = csv.writer(outfile)
out.writerows(map(lambda x: [x],list))
outfile.close()

2 个答案:

答案 0 :(得分:1)

尝试一下:

outfile = open('list.csv', 'w', newline='')
out = csv.writer(outfile)
out.writerows([list[i:i+4] for i in range(0, len(list), 4)])
outfile.close()

或使用with open

with open('list.csv', 'w', newline='') as outfile:
    out = csv.writer(outfile)
    out.writerows([list[i:i+4] for i in range(0, len(list), 4)])

答案 1 :(得分:0)

import csv 
a = [1, 2, 3, 4, 5, 6, 7, 8]

with open('test.csv', 'w', newline='') as fout:
    w = csv.writer(fout)
    w.writerow(a[:4])
    w.writerow(a[4:])