4

How I can write into a csv file in python so that,a list(which is a list of lists)

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

in the following format:

CL07001006 IM75630511 CL0700100r
IM20010809 IM75550511 CL0700100U
           IM75610511 PL07001006
           IM75640511
           IM75500511

I have tried something like below:

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

which results in like below:

CL07001006
IM20010809
IM75630511
IM75610511
IM75640511
IM75500511

Thanks.

2
  • 1
    You'll need to transpose the lists (making rows columns) and fill in the missing values with None. After than you can use csv.writerows Commented May 14, 2012 at 17:37
  • 1
    A CSV file would have rows of the format "CL07001006,IM75630511,CL0700100r\n". Is this what you want? Commented May 14, 2012 at 17:40

1 Answer 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,
Sign up to request clarification or add additional context in comments.

1 Comment

itertools.izip_longest is an excellent find and more elegant than my solution. I've deleted mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.