编辑csv文件Python 3 - 将文件内容与打印输出匹配

时间:2016-04-03 18:03:49

标签: python csv python-3.x

我遇到了将创建的csv文件的内容显示为打印输出的问题。

代码:

import csv

with open('test.csv', 'w', newline='') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=' ',
                            quotechar=',', quoting=csv.QUOTE_MINIMAL)
    filewriter.writerow(['Spam'] * 2 + ['Baked Beans'])
    filewriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

with open('test.csv', newline='') as csvfile:
     filereader = csv.reader(csvfile, delimiter=' ', quotechar=',')
     for row in filereader:
         print(', '.join(row))

输出:

Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

test.csv档案:

Spam Spam ,Baked Beans,
Spam ,Lovely Spam, ,Wonderful Spam,

注意奇怪的逗号。

test.csv

的所需内容
Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam

1 个答案:

答案 0 :(得分:0)

获得此输出的原因是因为您使用逗号quotechar=','来引用包含空格的字段,这是您的分隔符。这就是说你想要的是使用,作为默认delimiter value的分隔符。

import csv

with open('test.csv', 'w', newline='') as csvfile:
    filewriter = csv.writer(csvfile)
    filewriter.writerow(['Spam'] * 2 + ['Baked Beans'])
    filewriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

如果您想阅读csv文件,同样适用。