4

我如何在 python 中写入 csv 文件,这样,一个列表(这是一个列表的列表)

[['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511', 'IM75640511', 'IM75500511'],['CL0700100r','CL0700100U','PL07001006']]

采用以下格式:

CL07001006 IM75630511 CL0700100r
IM20010809 IM75550511 CL0700100U
           IM75610511 PL07001006
           IM75640511
           IM75500511

我尝试过类似下面的方法:

def demo():
    lol = [['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511',  'IM75640511', 'IM75500511']]
    file = open("dummy.csv", 'wb')
    fileWritter = csv.writer(file, delimiter='\n',quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for l in lol:
        fileWritter.writerow(l)


if __name__ == '__main__':
    demo()

结果如下:

CL07001006
IM20010809
IM75630511
IM75610511
IM75640511
IM75500511

谢谢。

4

1 回答 1

3
>>> import itertools
>>> import csv
>>> x = [['CL07001006', 'IM20010809'], ['IM75630511', 'IM75550511', 'IM75610511', 'IM75640511', 'IM75500511'],['CL0700100r','CL0700100U','PL07001006']]
>>> outs = csv.writer(open("out.csv", "wb"))
>>> for row in itertools.izip_longest(*x):
...     outs.writerow(row)
...
>>> ^D

$ cat "out.csv"
CL07001006,IM75630511,CL0700100r
IM20010809,IM75550511,CL0700100U
,IM75610511,PL07001006
,IM75640511,
,IM75500511,
于 2012-05-14T17:40:30.623 回答