2014-07-03 263 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])