CSV模块用于在列表中写入新行数据

时间:2014-09-14 14:17:16

标签: python python-2.7 csv

我的列表如下,

lista=["a","b","c","\n","d","e","f","\n","g","h","i","\n"]

有人可以告诉我如何让csv模块写这个,以便每个" \ n"在列表中被计为换行符?为了简化,csv应该是这样的,

a,b,c

d,e,f

g,h,i

如果问题不明确,请告诉我,我会根据需要进行更改。

2 个答案:

答案 0 :(得分:1)

import csv
import sys

def rows(lst):
    it = iter(lst)
    while True:
        row = list(iter(it.next, '\n'))  # it.__next__ in Python 3.x
        if not row:
            break
        yield row

lista = ["a","b","c","\n","d","e","f","\n","g","h","i","\n"]
writer = csv.writer(sys.stdout)  # Replace sys.stdout with file object
writer.writerows(rows(lista))

答案 1 :(得分:0)

您真的不需要CSV模块:

for s in ','.join(lista).split('\n'):
    print(s.strip(','), '\n')

这给出了:

a,b,c

d,e,f

g,h,i