如何从python列表生成CSV文件,每个列表项都在sep中

2024-09-28 05:25:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过从另一个问题得到的一些代码(listofpaths是我在代码前面生成的一个列表)

myfile = open('/home/graham/Desktop/Experiment/listcsv.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(list_of_paths)

但它把整个名单放在一个单元格里。我想把每一项放在不同的一行。我用于CSV文件的程序是libreofficecalc,如果这有区别的话。你知道吗


Tags: csv代码home列表openwrmyfilewriter
2条回答

我将使用标准的输入/输出来实现这一点。你知道吗

$ cat getCSV.py 
input_list = range(10)   # replace range(10) with your list
for elem in input_list:
    print '"' + str(elem) + '"'

$ python getCSV.py > output.csv
$ cat output.csv 
"0"
"1"
"2"
"3"
"4"
"5"
"6"
"7"
"8"
"9"

如果列表中的每个元素都是一个列表或元组。。可以使用join命令将它们分隔为列。你知道吗

>>> row = [str(i) for i in range(10)]
>>> row
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> ','.join(row)
'0,1,2,3,4,5,6,7,8,9'
>>> ','.join(['"' + col + '"' for col in row])
'"0","1","2","3","4","5","6","7","8","9"'

使用writerows如下:

myfile = open('/home/graham/Desktop/Experiment/listcsv.csv', 'wb')
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows([path] for path in list_of_paths)

相关问题 更多 >

    热门问题