Python, transposing a list and writing to a CSV file

后端 未结 3 986
时光取名叫无心
时光取名叫无心 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:50

    If you are using Python3 you need to open files in text format "wt", more over csv has writerows that can be used to write everything at once. here is an example:

    data=[("test", "value1", "value2"), ("test2", "value3", "value4")]
    with open('my.csv','wt') as out:
       csv_out=csv.writer(out)
       csv_out.writerows(data)
    

    I've just noticed that the question ask how to transform the list, that is a separate step and here is how I would do it:

    lol = [[1,2,3],[4,5,6]]
    data = zip(lol[0],lol[1])
    

提交回复
热议问题