[英]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.