Python, transposing a list and writing to a CSV file

后端 未结 3 980
时光取名叫无心
时光取名叫无心 2020-12-13 20:52

I need to write into a csv file using python and each iterator item should start in a new line. So delimiter I am using is \"\\n\". After each list has been written,next lis

3条回答
  •  执笔经年
    2020-12-13 21:34

    first transpose your input by using zip()

    >>> zip(*lol)
    [(1, 4), (2, 5), (3, 6)]
    

    and after that just pass it to csw.writer e.g.

    with open("test.csv", "wb") as f:
        fileWriter = csv.writer(f, delimiter=',',quotechar='|', quoting=csv.QUOTE_MINIMAL)
        for row in zip(*lol):
            fileWriter.writerow(row)
    

    ... which results to:

    $ cat test.csv 
    1,4
    2,5
    3,6
    

提交回复
热议问题