CSV读卡器重复读取1 lin

2024-04-19 02:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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次。你知道吗


Tags: 文件csvinimportforaswithopen
1条回答
网友
1楼 · 发布于 2024-04-19 02:36:26

你的代码正在做你让它做的事情。。。 (而且,你的标题也有误导性:读者只阅读了一次,你只是打印了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

相关问题 更多 >