[英]Python write to list to CSV
我对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'
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)
您必须迭代列表项,例如
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.