在python中将一系列数字输出到一个单元格中的csv文件中作为字符串

时间:2014-10-25 02:05:27

标签: python string csv

我正在尝试将一系列数字写入csv文件。但是所有数字都应该在一个单元格中,并用","分隔。

seq = str((554, 551, 553, 563, 562, 575, 581, 560, 576, 577, 578, 579))

with open('VROutput.csv', "wb") as csvfile:
    writer = csv.writer(csvfile,  delimiter=',', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(('Game', 'Year', 'Month', 'Day', 'Hour', 'Minute', 'Open Table', 'Opening Order'))
    for s, t, i in set((s, t, i) for s, t, i, p, n, k in combo):
         writer.writerow((i, '2014', '8', day, t, '00', quicksum(x[s, (int(t)), i, p, n, k].x for s, t, i, p, n, k   
combo.select(s, t, i, p, '*', '*')), seq))

在输出文件i中,每行中的最后一个单元格为seq,但我不想看到任何括号或括号或数字周围的任何内容。我希望在每一行的最后一个单元格中打印出554, 551, 553, 563, 562, 575, 581, 560, 576, 577, 578, 579

2 个答案:

答案 0 :(得分:0)

>>> ','.join(map(str,(554, 551, 553, 563, 562, 575, 581, 560, 576, 577, 578, 579)))
'554,551,553,563,562,575,581,560,576,577,578,579'
>>> 

答案 1 :(得分:0)

我不确定您确切的所需输出,并且我简化了您发布的代码以使其运行,但如果您将seq定义为列表并执行此操作:

import csv

seq= [554,551,553,563,562,575,581,560,576,577,578,579]
writer=csv.writer(open('testFile.csv','wb'))
for i in range(3):
        outLists = [[i,'2014','8',1,4,'00'],[str(val) for val in seq]]
        outFin = [item for subList in outLists for item in subList]
        writer.writerow(outFin)

您将获得没有任何引号或括号的输出:

0,2014,8,1,4,00,554,551,553,563,562,575,581,560,576,577,578,579
1,2014,8,1,4,00,554,551,553,563,562,575,581,560,576,577,578,579
2,2014,8,1,4,00,554,551,553,563,562,575,581,560,576,577,578,579

然而wwii的回答会在你的最后一个单元格周围加上引号,这可能在文本编辑器中看起来不对,但是会制作像MS Excel这样的软件,创建一个你想要的最终单元格。这将在文本编辑器中显示如下:

0,2014,8,1,4,00,"554,551,553,563,562,575,581,560,576,577,578,579"
1,2014,8,1,4,00,"554,551,553,563,562,575,581,560,576,577,578,579"
2,2014,8,1,4,00,"554,551,553,563,562,575,581,560,576,577,578,579"

由此代码生成:

import csv

seq = ','.join(map(str,(554, 551, 553, 563, 562, 575, 581, 560, 576, 577, 578, 579)))
'554,551,553,563,562,575,581,560,576,577,578,579'
writer=csv.writer(open('testFile.csv','wb'))
for i in range(3):
        withQuotes = (i,'2014','8',1,4,'00',seq)
        writer.writerow(withQuotes)