Writing multiple lists to csv Python

前端 未结 2 369
故里飘歌
故里飘歌 2021-01-23 20:27

Im trying to write a function that writes multiple lists to a singular csv file and i am able to get the column titles to write, but not any of the data. My data is in lists tha

2条回答
  •  情话喂你
    2021-01-23 21:07

    As the name implies, writerows writes rows, not columns. Furthermore, your lists are not equally sized, so you'll need to do something to account for that. The standard way of handling such a thing is using itertools.zip_longest.

    from itertools import zip_longest # izip_longest in python2.x
    
    with open("assignment_7_results.csv", "w") as f:
        w = csv.writer(f)
        w.writerow(["Number of Words", "Words/Sentence"])
        for x, y in zip_longest(number_of_words_sentence, mean_word_per_sentence):
            w.writerow([x, y])
    

提交回复
热议问题