【问题标题】:writerow() or writerows() loopswriterow() 和 writerows() 循环
【发布时间】:2012-09-26 11:54:51
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: python loops csv


    【解决方案1】:

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

    input_file = csv.reader(open('template.csv','r+')) #template.csv has 10 lines
    input_lines = list(input_file)
    

    【讨论】:

      【解决方案2】:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-11
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多