Writing Python lists to columns in csv

后端 未结 7 729

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:48

    I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:

    import csv
    list1 = ['a', 'b', 'c', 'd', 'e']
    list2 = ['f', 'g', 'i', 'j','k']
    with open('C:/test/numbers.csv', 'wb+') as myfile:
        wr = csv.writer(myfile)
        wr.writerow(("list1", "list2"))
        rcount = 0
        for row in list1:
            wr.writerow((list1[rcount], list2[rcount]))
            rcount = rcount + 1
        myfile.close()
    

提交回复
热议问题