2014-07-03 219 views
0

我寫入CSV語句無法正常工作;Python將列表寫入CSV

我有一個列表中的每個字符串都需要寫入他們自己的行在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) 

問題是,我的輸出被搞亂了,看起來像這樣;

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

我需要;

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

回答

3

csvwriter.writerows應與序列(或可迭代)一起使用。 (該mylist也是序列的序列,因爲字符串可以被看作是一個序列的單字符字符串)

使用csvwriter.writerow爲每mylist物品來代替:

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

要使用writerows,轉換列表對序列的序列:

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

你必須遍歷列表中的項目,如

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