我遇到了将创建的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
答案 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
文件,同样适用。