我正在尝试在包含5个元组的列表中编写项目,每个元组有5个项目(1个字符串4个整数)。我试图将它们写入csv文件。尽管使用delimiter = ','
,我仍然将每个元组放在1个单元格中。我想要做的是将每个元组放在一个单独的行中,并将这些元组中的每个项放在它们自己的单元格中。
这是我正在使用的代码和列表。此函数位于对象类中,其他所有工作正常。
代码:
[('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)
任何帮助将不胜感激。感谢。
答案 0 :(得分: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"