[英]CSV reader repeatedly reading 1 line
I have a csv.reader
reading a file, but repeatedly reading the same 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
The code prints the second row (as I want to skip the header) 10 times. 该代码将第二行打印10次(因为我想跳过标题)。
Your code is doing exactly what you told it to do... (and also, your title is misleading: the reader is reading the row only once, you are simply printing it 10 times) 您的代码完全按照您的要求进行操作...(而且,您的标题具有误导性:读者只读取该行一次,您只是将其打印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.
Why do you have that while loop in the first place? 为什么首先要有while循环? You could easily do something like:
您可以轻松地执行以下操作:
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.