Python将列表写入CSV
我的write to CSV语句工作不正常 我有一个列表,每个列表中都有字符串,每个字符串都需要在csv中写入到自己的行中Python将列表写入CSV,python,list,csv,Python,List,Csv,我的write to 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) 问题是,我的输出在某个地方出错了,看起来像这样 '
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'
应与序列(或iterable)一起使用。(mylist的mylist
也是一个序列,因为字符串可以看作是一个单字符串序列)
改为用于每个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)
您必须迭代列表项,如
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])