繁体   English   中英

CSV阅读器重复阅读1行

[英]CSV reader repeatedly reading 1 line

我有一个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次(因为我想跳过标题)。

您的代码完全按照您的要求进行操作...(而且,您的标题具有误导性:读者只读取该行一次,您只是将其打印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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM