我有以下代码:
import csv
input_file = csv.reader(open('template.csv','r+')) #template.csv has 10 lines
output = open('output.csv', 'wb')
wr = csv.writer(output, quoting=csv.QUOTE_ALL)
elem = [1,2,3,4,5]
for i in elem:
wr.writerows(input_file)
由于'template.csv'文件有10行,我希望输出10 x 5行 - 但只有10行。
如何嵌套writerow / rows循环?
答案 0 :(得分:6)
你input_file
是一个迭代器,一旦筋疲力尽就不会为你回到起点。将结果存储在列表中并写下:
input_file = csv.reader(open('template.csv','r+')) #template.csv has 10 lines
input_lines = list(input_file)
答案 1 :(得分:0)
writerows :将根据您在csv.writer中设置的规则创建csv,例如
wr = csv.writer(csvfile, delimiter='\n') #this will output each element in input_file
#as a separate line
#Loop it 5 times you should have your 5 x 10 lines printed to the file
for i in elem[0:4]:
wr.writerows(input_file)