Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python将列表写入CSV_Python_List_Csv - Fatal编程技术网

Python将列表写入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) 问题是,我的输出在某个地方出错了,看起来像这样 '

我的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)
问题是,我的输出在某个地方出错了,看起来像这样

'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])