2016-04-03 84 views
1

我在創建csv文件的內容時顯示爲打印輸出時遇到問題。編輯csv文件Python 3 - 將文件內容與打印輸出相匹配

代碼:

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

您得到這個輸出的原因所需的內容,是因爲你正在使用逗號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文件同樣的事情適用。