csv.writer writing each character of word in separate column/cell csv.writer writing each character of word in separate column/cell python python

csv.writer writing each character of word in separate column/cell


.writerow() requires a sequence ('', (), []) and places each index in it's own column of the row, sequentially. If your desired string is not an item in a sequence, writerow() will iterate over each letter in your string and each will be written to your CSV in a separate cell.

after you import csv

If this is your list:

myList = ['Diamond', 'Sierra', 'Crystal', 'Bridget', 'Chastity', 'Jasmyn', 'Misty', 'Angel', 'Dakota', 'Asia', 'Desiree', 'Monique', 'Tatiana']listFile = open('Names.csv', 'wb')writer = csv.writer(listFile)for item in myList:    writer.writerow(item)

The above script will produce the following CSV:Names.csv

D,i,a,m,o,n,dS,i,e,r,r,aC,r,y,s,t,a,lB,r,i,d,g,e,tC,h,a,s,t,i,t,yJ,a,s,m,y,nM,i,s,t,yA,n,g,e,lD,a,k,o,t,aA,s,i,aD,e,s,i,r,e,eM,o,n,i,q,u,eT,a,t,i,a,n,a

If you want each name in it's own cell, the solution is to simply place your string (item) in a sequence. Here I use square brackets []. :

listFile2 = open('Names2.csv', 'wb')writer2 = csv.writer(listFile2)for item in myList:    writer2.writerow([item])

The script with .writerow([item]) produces the desired results:Names2.csv

DiamondSierraCrystalBridgetChastityJasmynMistyAngelDakotaAsiaDesireeMoniqueTatiana


writerow accepts a sequence. You're giving it a single string, so it's treating that as a sequence, and strings act like sequences of characters.

What else do you want in this row? Nothing? If so, make it a list of one item:

spamwriter.writerow([u' '.join(model.a.stripped_strings).encode('utf8').strip()])

(By the way, the unicode() call is completely unnecessary since you're already joining with a unicode delimiter.)


This is usually the solution I use:

import csv    with open("output.csv", 'w', newline= '') as output:        wr = csv.writer(output, dialect='excel')        for element in list_of_things:            wr.writerow([element])        output.close()

This should provide you with an output of all your list elements in a single column rather than a single row.

Key points here is to iterate over the list and use '[list]' to avoid the csvwriter sequencing issues.

Hope this is of use!