Brian Brian - 3 months ago 15
Python Question

How to write list to csv, with each item on a new row

I am having trouble writing a list of items into a csv file, with each item being on a new row. Here is what I have, it does what I want, except it is putting each letter on a new row...

import csv

data = ['First Item', 'Second Item', 'Third Item']
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
for i in data:
writer.writerows(i)

Answer

Use a nested list: writer.writerows([[i]]). Explanation from writing data from a python list to csv row-wise:

.writerow takes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column.

So, as all you need is a single column, ...