CSV阅读器反复阅读1行

时间:2014-10-15 14:02:58

标签: python csv

我有一个csv.reader读取文件,但重复阅读同一行。

import csv

with open('mydata.csv', 'rb') as f:
    reader = csv.reader(f)
    reader.next()
    for row in reader:
        while i < 10:
            print row
            i=i+1

代码打印第二行(因为我想跳过标题)10次。

1 个答案:

答案 0 :(得分:2)

你的代码完全正是你告诉它做的...... (而且,你的标题是误导性的:读者只读了一次这行,你只是打印了10次)

reader.next() # advances to second line
for row in reader: # loops over remaining lines
    while i < 10: # loops over i
        print row # prints current row - this would be the second row in the first forloop iteration... 10 times, because you loop over i.
        i=i+1 # increments i, so the next rows, i is already >=10, your while-loop only affects the second line.

为什么你首先拥有while循环? 您可以轻松地执行以下操作:

   reader = csv.reader(f)
   for rownum, row in enumerate(reader):
     if rownum: #skip first line
        print row