0

我正在尝试从 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 语句来检查我是否在列表的末尾?但我不太确定该怎么做。

4

2 回答 2

0

你只需要Remove the text_file.write(c) line.
它只是造成额外的逗号。

于 2013-09-05T19:41:12.470 回答
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
于 2013-09-05T19:56:57.687 回答