Writing Python lists to columns in csv

后端 未结 7 726

I have 5 lists, all of the same length, and I\'d like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:

with open         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 19:39

    The following code writes python lists into columns in csv

    import csv
    from itertools import zip_longest
    list1 = ['a', 'b', 'c', 'd', 'e']
    list2 = ['f', 'g', 'i', 'j']
    d = [list1, list2]
    export_data = zip_longest(*d, fillvalue = '')
    with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
          wr = csv.writer(myfile)
          wr.writerow(("List1", "List2"))
          wr.writerows(export_data)
    myfile.close()
    

    The output looks like this

提交回复
热议问题