1

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)
Brian
  • 715
  • 4
  • 16
  • 37

2 Answers2

6

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, ...

Community
  • 1
  • 1
a small orange
  • 560
  • 2
  • 16
0
import csv   

example_list = [1,2,3,4]
resultFile = open("CSV_file_Name.csv", 'a')
wr = csv.writer(resultFile, dialect='excel')
length_list = len(example_list)
i = 0
while i!=length_list:
    wr.writerow(example_list[i:i+1])
    i+=1
resultFile.close()
rahul
  • 1
  • 1
  • While this code snippet may solve the problem, **[including an explanation](//meta.stackexchange.com/q/114762) really helps to improve the quality of your post**. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – dan1st Sep 11 '20 at 12:46