简体   繁体   English

将列表放入csv

[英]Putting list into csv

I have a list in Python 3. I want to split a list [1,2,3,4,5,6,7,8] to [1,2,3,4] in one row and [5,6,7,8] the other.我在 Python 3 中有一个列表。我想在一行中将列表 [1,2,3,4,5,6,7,8] 拆分为 [1,2,3,4] 和 [5,6, 7,8] 其他。 I am currently using this to write to CSV however I am doing the split manually and there will be a blank cell after it writes not sure how to get rid of it that's another problem also我目前正在使用它来写入 CSV,但是我正在手动进行拆分,并且在写入后会出现一个空白单元格,不确定如何摆脱它,这也是另一个问题

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

Try this:尝试这个:

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()

Or with with open :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)])
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:])

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

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