Write lists of different size to csv in columns in Python

前端 未结 2 560
不知归路
不知归路 2021-01-23 07:39

I need to write lists that all differ in length to a CSV file in columns.

I currently have:

d=lists
writer = csv.writer(fl)
for values in zip(*d):
    wr         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 08:39

    Code below is for Python 3. If you use Python 2, import izip_longest instead of zip_longest.

    import csv
    from itertools import zip_longest
    
    d = [[2,3,4,8],[5,6]]
    
    with open("file.csv","w+") as f:
        writer = csv.writer(f)
        for values in zip_longest(*d):
            writer.writerow(values)
    

    Result:

    2,5
    3,6
    4,
    8,
    

提交回复
热议问题