我对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'
答案 0 :(得分:3)
csvwriter.writerows
应与序列的序列(或可迭代)一起使用。 (mylist
也是一系列序列,因为字符串可以看作是一系列单字符串)
对每个mylist
项目使用csvwriter.writerow
代替:
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 :(得分:-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])