2016-01-04 21 views
1

我想在包含5個元組的列表中寫入項目,每個元組都有5個項目(1個字符串4個整數)。我正在嘗試將它們寫入一個csv文件。儘管使用了delimiter = ',',但我始終將每個元組都放在1個單元中。我想要做的是將每個元組放在一個單獨的行中,並將這些元組中的每個元素放在它們自己的單元格中。 這是我使用的代碼和列表。這個函數是在一個對象類中,而其他所有工作都正常。在寫入csv時列表中的元組中的單獨項目

代碼:

[('Endurance', 112, 150, 121, 136), ('Tempo', 152, 190, 138, 142), 
('Threshold', 192, 210, 144, 150), ('VO2', 212, 240, 152, 155), 
('Anaerobic', 242, 300, 156, 161)] 

def writeCSV(self,l): 

    with open('tz.csv', 'wb') as myfile: 
     wr = csv.writer(myfile, delimiter = ',', quoting=csv.QUOTE_ALL) 
     wr.writerow(l) 

任何幫助,將不勝感激。謝謝。

回答

1

使用writer.writerows()寫行的整個列表:

import csv 
lst = [('Endurance', 112, 150, 121, 136), ('Tempo', 152, 190, 138, 142), 
     ('Threshold', 192, 210, 144, 150), ('VO2', 212, 240, 152, 155), 
     ('Anaerobic', 242, 300, 156, 161)] 

def write_csv(lst): 

    with open('tz.csv', 'wb') as myfile: 
     wr = csv.writer(myfile, delimiter = ',', quoting=csv.QUOTE_ALL) 
     wr.writerows(lst) 

write_csv(lst) 

文件內容:

"Endurance","112","150","121","136" 
"Tempo","152","190","138","142" 
"Threshold","192","210","144","150" 
"VO2","212","240","152","155" 
"Anaerobic","242","300","156","161" 
+0

非常感謝!工作完美! –

相關問題