在列表结束后删除逗号

时间:2013-09-05 19:15:26

标签: python csv file-io

我正在尝试从cvs文件中读取并将输出写入txt文档:

import csv

reader = csv.reader(open('C:\Python33\excel.csv', newline=''), delimiter=' ', quotechar='|')
text_file = open("C:\Python33\output.txt", "w")
c = ", "

for row in reader:
    text_file.write(', '.join(row))
    text_file.write(c)

#reader.close()
text_file.close()

当前输出如下:

current: `beef, chicken, corn, cheese, yogurt, hippo,`

desired: `beef, chicken, corn, cheese, yogurt, hippo`

我想删除列表末尾的逗号,我想要一个if语句来检查我是否在列表的末尾?但我不太清楚该怎么做。

2 个答案:

答案 0 :(得分:0)

你必须Remove the text_file.write(c) line.
这只会引起额外的逗号。

答案 1 :(得分:0)

将所有行存储在列表中,然后将它们与join连接在一起。

import csv

reader = csv.reader(open('C:\Python33\excel.csv', newline=''), delimiter=' ', quotechar='|')
text_file = open("output.txt", "w")

lines = []
for row in reader:
    lines.append(', '.join(row))

output = ", ".join(lines)
print(output)

结果:

beef, chicken, corn, cheese, yogurt, hippo