MorganTN
MorganTN

Reputation: 2907

Python write to list to CSV

My write to CSV statement isn't working properly;

I have a list with strings in each that each need to be written to their own line in csv;

mylist = ['this is the first line','this is the second line'........]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(mylist)

The problem is, my output gets messed up somewhere and looks like this;

't,h,i,s, i,s, t,h,e, f,i,r,s,t, l,i,n,e,'.... etc.

I need to be;

'this is the first line'
'this is the second line'

Upvotes: 1

Views: 390

Answers (2)

falsetru
falsetru

Reputation: 368894

csvwriter.writerows should be used with sequence (or iterable) of sequences. (The mylist is also a sequence of sequences because string can be seen as a sequence of single-character-strings)

Use csvwriter.writerow for every mylist items instead:

mylist = ['this is the first line','this is the second line'........]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    for row in mylist:
        writer.writerow([row])

To use writerows, convert the list to sequence of sequences:

mylist = ['this is the first line','this is the second line'........]
with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    rows = [[row] for row in mylist]
    writer.writerows(rows)

Upvotes: 4

ramchauhan
ramchauhan

Reputation: 238

You have to iterate the list items like

  mylist = ['this is the first line','this is the second line']
  with open("output.csv", "wb") as f:
      writer = csv.writer(f)
      for item in mylist:
          writer.writerow([item])

Upvotes: -1

Related Questions