简体   繁体   中英

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'

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)

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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM