Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/29.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 如何使用open()输出特定的csv格式?_Python_Excel_List_Csv - Fatal编程技术网

Python 如何使用open()输出特定的csv格式?

Python 如何使用open()输出特定的csv格式?,python,excel,list,csv,Python,Excel,List,Csv,我试图使用csv和os库将python列表写入csv文件 以下是我目前得到的信息: from os import path import csv import os example_list=[1,2,3,4,5] file_path=path.relpath("path") with open(file_path, mode='w') as f: list_writer = csv.writer(f, delimiter=',') for ele

我试图使用
csv
os
库将python列表写入csv文件

以下是我目前得到的信息:

from os import path
import csv 
import os

example_list=[1,2,3,4,5]

file_path=path.relpath("path")

with open(file_path, mode='w') as f:
     list_writer = csv.writer(f, delimiter=',')
     for element in example_list:
        list_writer.writerow(element)
但是,当我在excel工作簿中打开它时,输出如下所示(其中每个水平空间表示一个新单元格):

我试图得到如下所示的预期输出(每个垂直空间代表一个新单元):


如何调整此函数以获得所需的输出?

您的代码产生以下错误:

_csv.Error: iterable expected, not int
写入行时,应在
元素
周围添加括号
[]
,以构建一个列表(这是一个iterable):

您还可以将
for
循环替换为:

list_writer.writerow(example_list)

您的代码出现以下错误
\u csv.error:应为iterable,而不是int
,因为您需要在
writerow()中传递iterable

此处
newline=''
避免添加额外的行空间

使用
writerows()的替代方法


writerow()
希望您像列表一样传递一个序列,但您传递的是单个元素(一个数字)。尝试
list\u writer.writerow([element])
。还要注意,文档中说要像这样打开csv文件:
open(file\u path,mode='w',newline='')
.add
open(file\u path,mode='w',newline='')
要去掉中间多余的单元格,确实需要添加
newline='
_csv.Error: iterable expected, not int
list_writer.writerow([element])
list_writer.writerow(example_list)
with open(path,'w',newline='') as f:
    list_writer = csv.writer(f, delimiter=',')
    for element in example_list:
        list_writer.writerow([element])
with open(path,'w',newline='') as f:
    list_writer = csv.writer(f, delimiter=',')
    list_writer.writerows([element] for element in example_list)