2

我有以下代码:

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 循环?

4

2 回答 2

6

input_file是一个迭代器,一旦用尽就不会为你倒回开始。将结果存储在列表中并写下:

input_file = csv.reader(open('template.csv','r+')) #template.csv has 10 lines
input_lines = list(input_file)
于 2012-10-05T10:30:29.070 回答
0

writerrows:将根据您在 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)
于 2014-08-07T14:24:08.917 回答